Fix svn:eol-style property.

git-svn-id: https://chromiumembedded.googlecode.com/svn/trunk@1470 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
This commit is contained in:
Marshall Greenblatt
2013-10-18 16:33:56 +00:00
parent bc90a7f854
commit 6a52564668
27 changed files with 4397 additions and 4397 deletions

View File

@ -1,64 +1,64 @@
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. // Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are // modification, are permitted provided that the following conditions are
// met: // met:
// //
// * Redistributions of source code must retain the above copyright // * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer. // notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above // * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer // copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the // in the documentation and/or other materials provided with the
// distribution. // distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded // * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse // Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior // or promote products derived from this software without specific prior
// written permission. // written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// //
// The contents of this file must follow a specific format in order to // The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the // support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information. // tools directory for more information.
// //
#ifndef CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ #ifndef CEF_INCLUDE_CEF_AUTH_CALLBACK_H_
#define CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ #define CEF_INCLUDE_CEF_AUTH_CALLBACK_H_
#pragma once #pragma once
#include "include/cef_base.h" #include "include/cef_base.h"
/// ///
// Callback interface used for asynchronous continuation of authentication // Callback interface used for asynchronous continuation of authentication
// requests. // requests.
/// ///
/*--cef(source=library)--*/ /*--cef(source=library)--*/
class CefAuthCallback : public virtual CefBase { class CefAuthCallback : public virtual CefBase {
public: public:
/// ///
// Continue the authentication request. // Continue the authentication request.
/// ///
/*--cef(capi_name=cont)--*/ /*--cef(capi_name=cont)--*/
virtual void Continue(const CefString& username, virtual void Continue(const CefString& username,
const CefString& password) =0; const CefString& password) =0;
/// ///
// Cancel the authentication request. // Cancel the authentication request.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual void Cancel() =0; virtual void Cancel() =0;
}; };
#endif // CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ #endif // CEF_INCLUDE_CEF_AUTH_CALLBACK_H_

View File

@ -1,120 +1,120 @@
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. // Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are // modification, are permitted provided that the following conditions are
// met: // met:
// //
// * Redistributions of source code must retain the above copyright // * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer. // notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above // * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer // copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the // in the documentation and/or other materials provided with the
// distribution. // distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded // * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse // Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior // or promote products derived from this software without specific prior
// written permission. // written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// //
// The contents of this file must follow a specific format in order to // The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the // support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information. // tools directory for more information.
// //
#ifndef CEF_INCLUDE_CEF_DRAG_DATA_H_ #ifndef CEF_INCLUDE_CEF_DRAG_DATA_H_
#define CEF_INCLUDE_CEF_DRAG_DATA_H_ #define CEF_INCLUDE_CEF_DRAG_DATA_H_
#pragma once #pragma once
#include "include/cef_base.h" #include "include/cef_base.h"
#include <vector> #include <vector>
/// ///
// Class used to represent drag data. The methods of this class may be called // Class used to represent drag data. The methods of this class may be called
// on any thread. // on any thread.
/// ///
/*--cef(source=library)--*/ /*--cef(source=library)--*/
class CefDragData : public virtual CefBase { class CefDragData : public virtual CefBase {
public: public:
/// ///
// Returns true if the drag data is a link. // Returns true if the drag data is a link.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual bool IsLink() =0; virtual bool IsLink() =0;
/// ///
// Returns true if the drag data is a text or html fragment. // Returns true if the drag data is a text or html fragment.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual bool IsFragment() =0; virtual bool IsFragment() =0;
/// ///
// Returns true if the drag data is a file. // Returns true if the drag data is a file.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual bool IsFile() =0; virtual bool IsFile() =0;
/// ///
// Return the link URL that is being dragged. // Return the link URL that is being dragged.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetLinkURL() =0; virtual CefString GetLinkURL() =0;
/// ///
// Return the title associated with the link being dragged. // Return the title associated with the link being dragged.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetLinkTitle() =0; virtual CefString GetLinkTitle() =0;
/// ///
// Return the metadata, if any, associated with the link being dragged. // Return the metadata, if any, associated with the link being dragged.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetLinkMetadata() =0; virtual CefString GetLinkMetadata() =0;
/// ///
// Return the plain text fragment that is being dragged. // Return the plain text fragment that is being dragged.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetFragmentText() =0; virtual CefString GetFragmentText() =0;
/// ///
// Return the text/html fragment that is being dragged. // Return the text/html fragment that is being dragged.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetFragmentHtml() =0; virtual CefString GetFragmentHtml() =0;
/// ///
// Return the base URL that the fragment came from. This value is used for // Return the base URL that the fragment came from. This value is used for
// resolving relative URLs and may be empty. // resolving relative URLs and may be empty.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetFragmentBaseURL() =0; virtual CefString GetFragmentBaseURL() =0;
/// ///
// Return the name of the file being dragged out of the browser window. // Return the name of the file being dragged out of the browser window.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual CefString GetFileName() =0; virtual CefString GetFileName() =0;
/// ///
// Retrieve the list of file names that are being dragged into the browser // Retrieve the list of file names that are being dragged into the browser
// window. // window.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual bool GetFileNames(std::vector<CefString>& names) =0; virtual bool GetFileNames(std::vector<CefString>& names) =0;
}; };
#endif // CEF_INCLUDE_CEF_DRAG_DATA_H_ #endif // CEF_INCLUDE_CEF_DRAG_DATA_H_

View File

@ -1,66 +1,66 @@
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. // Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
// //
// Redistribution and use in source and binary forms, with or without // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are // modification, are permitted provided that the following conditions are
// met: // met:
// //
// * Redistributions of source code must retain the above copyright // * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer. // notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above // * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer // copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the // in the documentation and/or other materials provided with the
// distribution. // distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded // * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse // Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior // or promote products derived from this software without specific prior
// written permission. // written permission.
// //
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// //
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// //
// The contents of this file must follow a specific format in order to // The contents of this file must follow a specific format in order to
// support the CEF translator tool. See the translator.README.txt file in the // support the CEF translator tool. See the translator.README.txt file in the
// tools directory for more information. // tools directory for more information.
// //
#ifndef CEF_INCLUDE_CEF_DRAG_HANDLER_H_ #ifndef CEF_INCLUDE_CEF_DRAG_HANDLER_H_
#define CEF_INCLUDE_CEF_DRAG_HANDLER_H_ #define CEF_INCLUDE_CEF_DRAG_HANDLER_H_
#pragma once #pragma once
#include "include/cef_base.h" #include "include/cef_base.h"
#include "include/cef_drag_data.h" #include "include/cef_drag_data.h"
#include "include/cef_browser.h" #include "include/cef_browser.h"
/// ///
// Implement this interface to handle events related to dragging. The methods of // Implement this interface to handle events related to dragging. The methods of
// this class will be called on the UI thread. // this class will be called on the UI thread.
/// ///
/*--cef(source=client)--*/ /*--cef(source=client)--*/
class CefDragHandler : public virtual CefBase { class CefDragHandler : public virtual CefBase {
public: public:
typedef cef_drag_operations_mask_t DragOperationsMask; typedef cef_drag_operations_mask_t DragOperationsMask;
/// ///
// Called when an external drag event enters the browser window. |dragData| // Called when an external drag event enters the browser window. |dragData|
// contains the drag event data and |mask| represents the type of drag // contains the drag event data and |mask| represents the type of drag
// operation. Return false for default drag handling behavior or true to // operation. Return false for default drag handling behavior or true to
// cancel the drag event. // cancel the drag event.
/// ///
/*--cef()--*/ /*--cef()--*/
virtual bool OnDragEnter(CefRefPtr<CefBrowser> browser, virtual bool OnDragEnter(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDragData> dragData, CefRefPtr<CefDragData> dragData,
DragOperationsMask mask) { return false; } DragOperationsMask mask) { return false; }
}; };
#endif // CEF_INCLUDE_CEF_DRAG_HANDLER_H_ #endif // CEF_INCLUDE_CEF_DRAG_HANDLER_H_

View File

@ -1,36 +1,36 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can // reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file. // be found in the LICENSE file.
#include "libcef/browser/browser_pref_store.h" #include "libcef/browser/browser_pref_store.h"
#include "libcef/browser/media_capture_devices_dispatcher.h" #include "libcef/browser/media_capture_devices_dispatcher.h"
#include "base/command_line.h" #include "base/command_line.h"
#include "base/prefs/pref_service_builder.h" #include "base/prefs/pref_service_builder.h"
#include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_registry_simple.h"
#include "base/values.h" #include "base/values.h"
#include "chrome/browser/net/pref_proxy_config_tracker_impl.h" #include "chrome/browser/net/pref_proxy_config_tracker_impl.h"
#include "chrome/browser/prefs/command_line_pref_store.h" #include "chrome/browser/prefs/command_line_pref_store.h"
#include "chrome/browser/prefs/proxy_config_dictionary.h" #include "chrome/browser/prefs/proxy_config_dictionary.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
CefBrowserPrefStore::CefBrowserPrefStore() { CefBrowserPrefStore::CefBrowserPrefStore() {
} }
PrefService* CefBrowserPrefStore::CreateService() { PrefService* CefBrowserPrefStore::CreateService() {
PrefServiceBuilder builder; PrefServiceBuilder builder;
builder.WithCommandLinePrefs( builder.WithCommandLinePrefs(
new CommandLinePrefStore(CommandLine::ForCurrentProcess())); new CommandLinePrefStore(CommandLine::ForCurrentProcess()));
builder.WithUserPrefs(this); builder.WithUserPrefs(this);
scoped_refptr<PrefRegistrySimple> registry(new PrefRegistrySimple()); scoped_refptr<PrefRegistrySimple> registry(new PrefRegistrySimple());
// Default settings. // Default settings.
CefMediaCaptureDevicesDispatcher::RegisterPrefs(registry); CefMediaCaptureDevicesDispatcher::RegisterPrefs(registry);
PrefProxyConfigTrackerImpl::RegisterPrefs(registry); PrefProxyConfigTrackerImpl::RegisterPrefs(registry);
return builder.Create(registry); return builder.Create(registry);
} }
CefBrowserPrefStore::~CefBrowserPrefStore() { CefBrowserPrefStore::~CefBrowserPrefStore() {
} }

View File

@ -1,18 +1,18 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#include "libcef/browser/url_request_user_data.h" #include "libcef/browser/url_request_user_data.h"
CefURLRequestUserData::CefURLRequestUserData(CefRefPtr<CefURLRequestClient> client) CefURLRequestUserData::CefURLRequestUserData(CefRefPtr<CefURLRequestClient> client)
: client_(client) {} : client_(client) {}
CefURLRequestUserData::~CefURLRequestUserData() {} CefURLRequestUserData::~CefURLRequestUserData() {}
CefRefPtr<CefURLRequestClient> CefURLRequestUserData::GetClient() { CefRefPtr<CefURLRequestClient> CefURLRequestUserData::GetClient() {
return client_; return client_;
} }
// static // static
const void* CefURLRequestUserData::kUserDataKey = const void* CefURLRequestUserData::kUserDataKey =
static_cast<const void*>(&CefURLRequestUserData::kUserDataKey); static_cast<const void*>(&CefURLRequestUserData::kUserDataKey);

View File

@ -1,27 +1,27 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ #ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_
#define CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ #define CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_
#include "include/cef_base.h" #include "include/cef_base.h"
#include "base/supports_user_data.h" #include "base/supports_user_data.h"
#include "include/cef_urlrequest.h" #include "include/cef_urlrequest.h"
// Used to annotate all URLRequests for which the request can be associated // Used to annotate all URLRequests for which the request can be associated
// with the CefURLRequestClient. // with the CefURLRequestClient.
class CefURLRequestUserData : public base::SupportsUserData::Data { class CefURLRequestUserData : public base::SupportsUserData::Data {
public: public:
CefURLRequestUserData(CefRefPtr<CefURLRequestClient> client); CefURLRequestUserData(CefRefPtr<CefURLRequestClient> client);
virtual ~CefURLRequestUserData(); virtual ~CefURLRequestUserData();
CefRefPtr<CefURLRequestClient> GetClient(); CefRefPtr<CefURLRequestClient> GetClient();
static const void* kUserDataKey; static const void* kUserDataKey;
private: private:
CefRefPtr<CefURLRequestClient> client_; CefRefPtr<CefURLRequestClient> client_;
}; };
#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ #endif // CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_

View File

@ -1,63 +1,63 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#include "libcef/common/drag_data_impl.h" #include "libcef/common/drag_data_impl.h"
#include "base/files/file_path.h" #include "base/files/file_path.h"
CefDragDataImpl::CefDragDataImpl(const content::DropData& data) CefDragDataImpl::CefDragDataImpl(const content::DropData& data)
: data_(data) { : data_(data) {
} }
bool CefDragDataImpl::IsLink() { bool CefDragDataImpl::IsLink() {
return (data_.url.is_valid() && data_.file_description_filename.empty()); return (data_.url.is_valid() && data_.file_description_filename.empty());
} }
bool CefDragDataImpl::IsFragment() { bool CefDragDataImpl::IsFragment() {
return (!data_.url.is_valid() && data_.file_description_filename.empty() && return (!data_.url.is_valid() && data_.file_description_filename.empty() &&
data_.filenames.empty()); data_.filenames.empty());
} }
bool CefDragDataImpl::IsFile() { bool CefDragDataImpl::IsFile() {
return (!data_.file_description_filename.empty() || !data_.filenames.empty()); return (!data_.file_description_filename.empty() || !data_.filenames.empty());
} }
CefString CefDragDataImpl::GetLinkURL() { CefString CefDragDataImpl::GetLinkURL() {
return data_.url.spec(); return data_.url.spec();
} }
CefString CefDragDataImpl::GetLinkTitle() { CefString CefDragDataImpl::GetLinkTitle() {
return data_.url_title; return data_.url_title;
} }
CefString CefDragDataImpl::GetLinkMetadata() { CefString CefDragDataImpl::GetLinkMetadata() {
return data_.download_metadata; return data_.download_metadata;
} }
CefString CefDragDataImpl::GetFragmentText() { CefString CefDragDataImpl::GetFragmentText() {
return data_.text.is_null() ? CefString() : CefString(data_.text.string()); return data_.text.is_null() ? CefString() : CefString(data_.text.string());
} }
CefString CefDragDataImpl::GetFragmentHtml() { CefString CefDragDataImpl::GetFragmentHtml() {
return data_.html.is_null() ? CefString() : CefString(data_.html.string()); return data_.html.is_null() ? CefString() : CefString(data_.html.string());
} }
CefString CefDragDataImpl::GetFragmentBaseURL() { CefString CefDragDataImpl::GetFragmentBaseURL() {
return data_.html_base_url.spec(); return data_.html_base_url.spec();
} }
CefString CefDragDataImpl::GetFileName() { CefString CefDragDataImpl::GetFileName() {
return data_.file_description_filename; return data_.file_description_filename;
} }
bool CefDragDataImpl::GetFileNames(std::vector<CefString>& names) { bool CefDragDataImpl::GetFileNames(std::vector<CefString>& names) {
if (data_.filenames.empty()) if (data_.filenames.empty())
return false; return false;
std::vector<content::DropData::FileInfo>::const_iterator it = std::vector<content::DropData::FileInfo>::const_iterator it =
data_.filenames.begin(); data_.filenames.begin();
for (; it != data_.filenames.end(); ++it) for (; it != data_.filenames.end(); ++it)
names.push_back(it->path); names.push_back(it->path);
return true; return true;
} }

View File

@ -1,37 +1,37 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#ifndef CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ #ifndef CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_
#define CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ #define CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_
#pragma once #pragma once
#include <vector> #include <vector>
#include "include/cef_drag_data.h" #include "include/cef_drag_data.h"
#include "content/public/common/drop_data.h" #include "content/public/common/drop_data.h"
// Implementation of CefDragData. // Implementation of CefDragData.
class CefDragDataImpl : public CefDragData { class CefDragDataImpl : public CefDragData {
public: public:
explicit CefDragDataImpl(const content::DropData& data); explicit CefDragDataImpl(const content::DropData& data);
virtual bool IsLink(); virtual bool IsLink();
virtual bool IsFragment(); virtual bool IsFragment();
virtual bool IsFile(); virtual bool IsFile();
virtual CefString GetLinkURL(); virtual CefString GetLinkURL();
virtual CefString GetLinkTitle(); virtual CefString GetLinkTitle();
virtual CefString GetLinkMetadata(); virtual CefString GetLinkMetadata();
virtual CefString GetFragmentText(); virtual CefString GetFragmentText();
virtual CefString GetFragmentHtml(); virtual CefString GetFragmentHtml();
virtual CefString GetFragmentBaseURL(); virtual CefString GetFragmentBaseURL();
virtual CefString GetFileName(); virtual CefString GetFileName();
virtual bool GetFileNames(std::vector<CefString>& names); virtual bool GetFileNames(std::vector<CefString>& names);
protected: protected:
content::DropData data_; content::DropData data_;
IMPLEMENT_REFCOUNTING(CefDragDataImpl); IMPLEMENT_REFCOUNTING(CefDragDataImpl);
}; };
#endif // CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ #endif // CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_

View File

@ -1,8 +1,8 @@
Index: browser/devtools/devtools_http_handler_impl.cc Index: browser/devtools/devtools_http_handler_impl.cc
=================================================================== ===================================================================
--- browser/devtools/devtools_http_handler_impl.cc (revision 228917) --- browser/devtools/devtools_http_handler_impl.cc (revision 228917)
+++ browser/devtools/devtools_http_handler_impl.cc (working copy) +++ browser/devtools/devtools_http_handler_impl.cc (working copy)
@@ -542,9 +542,17 @@ @@ -542,9 +542,17 @@
DevToolsTarget* DevToolsHttpHandlerImpl::GetTarget(const std::string& id) { DevToolsTarget* DevToolsHttpHandlerImpl::GetTarget(const std::string& id) {
TargetMap::const_iterator it = target_map_.find(id); TargetMap::const_iterator it = target_map_.find(id);
@ -23,11 +23,11 @@ Index: browser/devtools/devtools_http_handler_impl.cc
} }
void DevToolsHttpHandlerImpl::OnThumbnailRequestUI( void DevToolsHttpHandlerImpl::OnThumbnailRequestUI(
Index: public/browser/devtools_http_handler_delegate.h Index: public/browser/devtools_http_handler_delegate.h
=================================================================== ===================================================================
--- public/browser/devtools_http_handler_delegate.h (revision 228917) --- public/browser/devtools_http_handler_delegate.h (revision 228917)
+++ public/browser/devtools_http_handler_delegate.h (working copy) +++ public/browser/devtools_http_handler_delegate.h (working copy)
@@ -39,6 +39,13 @@ @@ -39,6 +39,13 @@
// Creates new inspectable target. // Creates new inspectable target.
virtual scoped_ptr<DevToolsTarget> CreateNewTarget() = 0; virtual scoped_ptr<DevToolsTarget> CreateNewTarget() = 0;

View File

@ -1,8 +1,8 @@
Index: WebNode.cpp Index: WebNode.cpp
=================================================================== ===================================================================
--- WebNode.cpp (revision 158192) --- WebNode.cpp (revision 158192)
+++ WebNode.cpp (working copy) +++ WebNode.cpp (working copy)
@@ -175,7 +175,7 @@ @@ -175,7 +175,7 @@
void WebNode::addEventListener(const WebString& eventType, WebDOMEventListener* listener, bool useCapture) void WebNode::addEventListener(const WebString& eventType, WebDOMEventListener* listener, bool useCapture)
{ {
// Please do not add more eventTypes to this list without an API review. // Please do not add more eventTypes to this list without an API review.

View File

@ -1,8 +1,8 @@
Index: public/web/WebView.h Index: public/web/WebView.h
=================================================================== ===================================================================
--- public/web/WebView.h (revision 159695) --- public/web/WebView.h (revision 159695)
+++ public/web/WebView.h (working copy) +++ public/web/WebView.h (working copy)
@@ -447,6 +447,7 @@ @@ -447,6 +447,7 @@
// Sets whether select popup menus should be rendered by the browser. // Sets whether select popup menus should be rendered by the browser.
BLINK_EXPORT static void setUseExternalPopupMenus(bool); BLINK_EXPORT static void setUseExternalPopupMenus(bool);
@ -10,11 +10,11 @@ Index: public/web/WebView.h
// Visited link state -------------------------------------------------- // Visited link state --------------------------------------------------
Index: Source/web/ChromeClientImpl.cpp Index: Source/web/ChromeClientImpl.cpp
=================================================================== ===================================================================
--- Source/web/ChromeClientImpl.cpp (revision 159695) --- Source/web/ChromeClientImpl.cpp (revision 159695)
+++ Source/web/ChromeClientImpl.cpp (working copy) +++ Source/web/ChromeClientImpl.cpp (working copy)
@@ -875,7 +875,7 @@ @@ -875,7 +875,7 @@
PassRefPtr<PopupMenu> ChromeClientImpl::createPopupMenu(Frame& frame, PopupMenuClient* client) const PassRefPtr<PopupMenu> ChromeClientImpl::createPopupMenu(Frame& frame, PopupMenuClient* client) const
{ {
@ -23,11 +23,11 @@ Index: Source/web/ChromeClientImpl.cpp
return adoptRef(new ExternalPopupMenu(frame, client, m_webView->client())); return adoptRef(new ExternalPopupMenu(frame, client, m_webView->client()));
return adoptRef(new PopupMenuChromium(frame, client)); return adoptRef(new PopupMenuChromium(frame, client));
Index: Source/web/WebViewImpl.cpp Index: Source/web/WebViewImpl.cpp
=================================================================== ===================================================================
--- Source/web/WebViewImpl.cpp (revision 159695) --- Source/web/WebViewImpl.cpp (revision 159695)
+++ Source/web/WebViewImpl.cpp (working copy) +++ Source/web/WebViewImpl.cpp (working copy)
@@ -411,6 +411,7 @@ @@ -411,6 +411,7 @@
, m_fakePageScaleAnimationPageScaleFactor(0) , m_fakePageScaleAnimationPageScaleFactor(0)
, m_fakePageScaleAnimationUseAnchor(false) , m_fakePageScaleAnimationUseAnchor(false)
, m_contextMenuAllowed(false) , m_contextMenuAllowed(false)
@ -35,7 +35,7 @@ Index: Source/web/WebViewImpl.cpp
, m_doingDragAndDrop(false) , m_doingDragAndDrop(false)
, m_ignoreInputEvents(false) , m_ignoreInputEvents(false)
, m_compositorDeviceScaleFactorOverride(0) , m_compositorDeviceScaleFactorOverride(0)
@@ -3751,9 +3752,14 @@ @@ -3751,9 +3752,14 @@
updateLayerTreeViewport(); updateLayerTreeViewport();
} }
@ -51,11 +51,11 @@ Index: Source/web/WebViewImpl.cpp
} }
void WebViewImpl::startDragging(Frame* frame, void WebViewImpl::startDragging(Frame* frame,
Index: Source/web/WebViewImpl.h Index: Source/web/WebViewImpl.h
=================================================================== ===================================================================
--- Source/web/WebViewImpl.h (revision 159695) --- Source/web/WebViewImpl.h (revision 159695)
+++ Source/web/WebViewImpl.h (working copy) +++ Source/web/WebViewImpl.h (working copy)
@@ -424,7 +424,8 @@ @@ -424,7 +424,8 @@
// Returns true if popup menus should be rendered by the browser, false if // Returns true if popup menus should be rendered by the browser, false if
// they should be rendered by WebKit (which is the default). // they should be rendered by WebKit (which is the default).
@ -65,7 +65,7 @@ Index: Source/web/WebViewImpl.h
bool contextMenuAllowed() const bool contextMenuAllowed() const
{ {
@@ -727,6 +728,8 @@ @@ -727,6 +728,8 @@
bool m_contextMenuAllowed; bool m_contextMenuAllowed;

View File

@ -1,493 +1,493 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#include "cefclient/cefclient_osr_widget_gtk.h" #include "cefclient/cefclient_osr_widget_gtk.h"
// This value is defined in build/common.gypi and must be undefined here // This value is defined in build/common.gypi and must be undefined here
// in order for gtkglext to compile. // in order for gtkglext to compile.
#undef GTK_DISABLE_SINGLE_INCLUDES #undef GTK_DISABLE_SINGLE_INCLUDES
#include <gdk/gdk.h> #include <gdk/gdk.h>
#include <gdk/gdkkeysyms.h> #include <gdk/gdkkeysyms.h>
#include <glib-object.h> #include <glib-object.h>
#include <gtk/gtk.h> #include <gtk/gtk.h>
#include <gtk/gtkgl.h> #include <gtk/gtkgl.h>
#include <GL/gl.h> #include <GL/gl.h>
#include "include/cef_runnable.h" #include "include/cef_runnable.h"
#include "cefclient/util.h" #include "cefclient/util.h"
namespace { namespace {
gint glarea_size_allocation(GtkWidget* widget, gint glarea_size_allocation(GtkWidget* widget,
GtkAllocation* allocation, GtkAllocation* allocation,
OSRWindow* window) { OSRWindow* window) {
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
host->WasResized(); host->WasResized();
return TRUE; return TRUE;
} }
int get_cef_state_modifiers(guint state) { int get_cef_state_modifiers(guint state) {
int modifiers = 0; int modifiers = 0;
if (state & GDK_SHIFT_MASK) if (state & GDK_SHIFT_MASK)
modifiers |= EVENTFLAG_SHIFT_DOWN; modifiers |= EVENTFLAG_SHIFT_DOWN;
if (state & GDK_LOCK_MASK) if (state & GDK_LOCK_MASK)
modifiers |= EVENTFLAG_CAPS_LOCK_ON; modifiers |= EVENTFLAG_CAPS_LOCK_ON;
if (state & GDK_CONTROL_MASK) if (state & GDK_CONTROL_MASK)
modifiers |= EVENTFLAG_CONTROL_DOWN; modifiers |= EVENTFLAG_CONTROL_DOWN;
if (state & GDK_MOD1_MASK) if (state & GDK_MOD1_MASK)
modifiers |= EVENTFLAG_ALT_DOWN; modifiers |= EVENTFLAG_ALT_DOWN;
if (state & GDK_BUTTON1_MASK) if (state & GDK_BUTTON1_MASK)
modifiers |= EVENTFLAG_LEFT_MOUSE_BUTTON; modifiers |= EVENTFLAG_LEFT_MOUSE_BUTTON;
if (state & GDK_BUTTON2_MASK) if (state & GDK_BUTTON2_MASK)
modifiers |= EVENTFLAG_MIDDLE_MOUSE_BUTTON; modifiers |= EVENTFLAG_MIDDLE_MOUSE_BUTTON;
if (state & GDK_BUTTON3_MASK) if (state & GDK_BUTTON3_MASK)
modifiers |= EVENTFLAG_RIGHT_MOUSE_BUTTON; modifiers |= EVENTFLAG_RIGHT_MOUSE_BUTTON;
return modifiers; return modifiers;
} }
gint glarea_click_event(GtkWidget* widget, gint glarea_click_event(GtkWidget* widget,
GdkEventButton* event, GdkEventButton* event,
OSRWindow* window) { OSRWindow* window) {
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
CefBrowserHost::MouseButtonType button_type = MBT_LEFT; CefBrowserHost::MouseButtonType button_type = MBT_LEFT;
switch (event->button) { switch (event->button) {
case 1: case 1:
break; break;
case 2: case 2:
button_type = MBT_MIDDLE; button_type = MBT_MIDDLE;
break; break;
case 3: case 3:
button_type = MBT_RIGHT; button_type = MBT_RIGHT;
break; break;
default: default:
// Other mouse buttons are not handled here. // Other mouse buttons are not handled here.
return FALSE; return FALSE;
} }
CefMouseEvent mouse_event; CefMouseEvent mouse_event;
mouse_event.x = event->x; mouse_event.x = event->x;
mouse_event.y = event->y; mouse_event.y = event->y;
window->ApplyPopupOffset(mouse_event.x, mouse_event.y); window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = get_cef_state_modifiers(event->state); mouse_event.modifiers = get_cef_state_modifiers(event->state);
bool mouse_up = (event->type == GDK_BUTTON_RELEASE); bool mouse_up = (event->type == GDK_BUTTON_RELEASE);
if (!mouse_up) if (!mouse_up)
gtk_widget_grab_focus(widget); gtk_widget_grab_focus(widget);
int click_count = 1; int click_count = 1;
switch (event->type) { switch (event->type) {
case GDK_2BUTTON_PRESS: case GDK_2BUTTON_PRESS:
click_count = 2; click_count = 2;
break; break;
case GDK_3BUTTON_PRESS: case GDK_3BUTTON_PRESS:
click_count = 3; click_count = 3;
break; break;
default: default:
break; break;
} }
host->SendMouseClickEvent(mouse_event, button_type, mouse_up, click_count); host->SendMouseClickEvent(mouse_event, button_type, mouse_up, click_count);
return TRUE; return TRUE;
} }
gint glarea_move_event(GtkWidget* widget, gint glarea_move_event(GtkWidget* widget,
GdkEventMotion* event, GdkEventMotion* event,
OSRWindow* window) { OSRWindow* window) {
gint x, y; gint x, y;
GdkModifierType state; GdkModifierType state;
if (event->is_hint) { if (event->is_hint) {
gdk_window_get_pointer(event->window, &x, &y, &state); gdk_window_get_pointer(event->window, &x, &y, &state);
} else { } else {
x = (gint)event->x; x = (gint)event->x;
y = (gint)event->y; y = (gint)event->y;
state = (GdkModifierType)event->state; state = (GdkModifierType)event->state;
} }
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
CefMouseEvent mouse_event; CefMouseEvent mouse_event;
mouse_event.x = x; mouse_event.x = x;
mouse_event.y = y; mouse_event.y = y;
window->ApplyPopupOffset(mouse_event.x, mouse_event.y); window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = get_cef_state_modifiers(state); mouse_event.modifiers = get_cef_state_modifiers(state);
bool mouse_leave = (event->type == GDK_LEAVE_NOTIFY); bool mouse_leave = (event->type == GDK_LEAVE_NOTIFY);
host->SendMouseMoveEvent(mouse_event, mouse_leave); host->SendMouseMoveEvent(mouse_event, mouse_leave);
return TRUE; return TRUE;
} }
gint glarea_scroll_event(GtkWidget* widget, gint glarea_scroll_event(GtkWidget* widget,
GdkEventScroll* event, GdkEventScroll* event,
OSRWindow* window) { OSRWindow* window) {
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
CefMouseEvent mouse_event; CefMouseEvent mouse_event;
mouse_event.x = event->x; mouse_event.x = event->x;
mouse_event.y = event->y; mouse_event.y = event->y;
window->ApplyPopupOffset(mouse_event.x, mouse_event.y); window->ApplyPopupOffset(mouse_event.x, mouse_event.y);
mouse_event.modifiers = get_cef_state_modifiers(event->state); mouse_event.modifiers = get_cef_state_modifiers(event->state);
static const int scrollbarPixelsPerGtkTick = 40; static const int scrollbarPixelsPerGtkTick = 40;
int deltaX = 0; int deltaX = 0;
int deltaY = 0; int deltaY = 0;
switch (event->direction) { switch (event->direction) {
case GDK_SCROLL_UP: case GDK_SCROLL_UP:
deltaY = scrollbarPixelsPerGtkTick; deltaY = scrollbarPixelsPerGtkTick;
break; break;
case GDK_SCROLL_DOWN: case GDK_SCROLL_DOWN:
deltaY = -scrollbarPixelsPerGtkTick; deltaY = -scrollbarPixelsPerGtkTick;
break; break;
case GDK_SCROLL_LEFT: case GDK_SCROLL_LEFT:
deltaX = scrollbarPixelsPerGtkTick; deltaX = scrollbarPixelsPerGtkTick;
break; break;
case GDK_SCROLL_RIGHT: case GDK_SCROLL_RIGHT:
deltaX = -scrollbarPixelsPerGtkTick; deltaX = -scrollbarPixelsPerGtkTick;
break; break;
} }
host->SendMouseWheelEvent(mouse_event, deltaX, deltaY); host->SendMouseWheelEvent(mouse_event, deltaX, deltaY);
return TRUE; return TRUE;
} }
gint glarea_key_event(GtkWidget* widget, gint glarea_key_event(GtkWidget* widget,
GdkEventKey* event, GdkEventKey* event,
OSRWindow* window) { OSRWindow* window) {
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
CefKeyEvent key_event; CefKeyEvent key_event;
key_event.native_key_code = event->keyval; key_event.native_key_code = event->keyval;
key_event.modifiers = get_cef_state_modifiers(event->state); key_event.modifiers = get_cef_state_modifiers(event->state);
if (event->type == GDK_KEY_PRESS) { if (event->type == GDK_KEY_PRESS) {
key_event.type = KEYEVENT_RAWKEYDOWN; key_event.type = KEYEVENT_RAWKEYDOWN;
host->SendKeyEvent(key_event); host->SendKeyEvent(key_event);
} else { } else {
// Need to send both KEYUP and CHAR events. // Need to send both KEYUP and CHAR events.
key_event.type = KEYEVENT_KEYUP; key_event.type = KEYEVENT_KEYUP;
host->SendKeyEvent(key_event); host->SendKeyEvent(key_event);
key_event.type = KEYEVENT_CHAR; key_event.type = KEYEVENT_CHAR;
host->SendKeyEvent(key_event); host->SendKeyEvent(key_event);
} }
return TRUE; return TRUE;
} }
gint glarea_focus_event(GtkWidget* widget, gint glarea_focus_event(GtkWidget* widget,
GdkEventFocus* event, GdkEventFocus* event,
OSRWindow* window) { OSRWindow* window) {
CefRefPtr<CefBrowserHost> host = window->GetBrowserHost(); CefRefPtr<CefBrowserHost> host = window->GetBrowserHost();
host->SendFocusEvent(event->in == TRUE); host->SendFocusEvent(event->in == TRUE);
return TRUE; return TRUE;
} }
void widget_get_rect_in_screen(GtkWidget* widget, GdkRectangle* r) { void widget_get_rect_in_screen(GtkWidget* widget, GdkRectangle* r) {
gint x, y, w, h; gint x, y, w, h;
GdkRectangle extents; GdkRectangle extents;
GdkWindow* window = gtk_widget_get_parent_window(widget); GdkWindow* window = gtk_widget_get_parent_window(widget);
// Get parent's left-top screen coordinates. // Get parent's left-top screen coordinates.
gdk_window_get_root_origin(window, &x, &y); gdk_window_get_root_origin(window, &x, &y);
// Get parent's width and height. // Get parent's width and height.
gdk_drawable_get_size(window, &w, &h); gdk_drawable_get_size(window, &w, &h);
// Get parent's extents including decorations. // Get parent's extents including decorations.
gdk_window_get_frame_extents(window, &extents); gdk_window_get_frame_extents(window, &extents);
// X and Y calculations assume that left, right and bottom border sizes are // X and Y calculations assume that left, right and bottom border sizes are
// all the same. // all the same.
const gint border = (extents.width - w) / 2; const gint border = (extents.width - w) / 2;
r->x = x + border + widget->allocation.x; r->x = x + border + widget->allocation.x;
r->y = y + (extents.height - h) - border + widget->allocation.y; r->y = y + (extents.height - h) - border + widget->allocation.y;
r->width = widget->allocation.width; r->width = widget->allocation.width;
r->height = widget->allocation.height; r->height = widget->allocation.height;
} }
class ScopedGLContext { class ScopedGLContext {
public: public:
ScopedGLContext(GtkWidget* widget, bool swap_buffers) ScopedGLContext(GtkWidget* widget, bool swap_buffers)
: swap_buffers_(swap_buffers) { : swap_buffers_(swap_buffers) {
GdkGLContext* glcontext = gtk_widget_get_gl_context(widget); GdkGLContext* glcontext = gtk_widget_get_gl_context(widget);
gldrawable_ = gtk_widget_get_gl_drawable(widget); gldrawable_ = gtk_widget_get_gl_drawable(widget);
is_valid_ = gdk_gl_drawable_gl_begin(gldrawable_, glcontext); is_valid_ = gdk_gl_drawable_gl_begin(gldrawable_, glcontext);
} }
virtual ~ScopedGLContext() { virtual ~ScopedGLContext() {
if (is_valid_) { if (is_valid_) {
gdk_gl_drawable_gl_end(gldrawable_); gdk_gl_drawable_gl_end(gldrawable_);
if(swap_buffers_) { if(swap_buffers_) {
if (gdk_gl_drawable_is_double_buffered(gldrawable_)) if (gdk_gl_drawable_is_double_buffered(gldrawable_))
gdk_gl_drawable_swap_buffers(gldrawable_); gdk_gl_drawable_swap_buffers(gldrawable_);
else else
glFlush(); glFlush();
} }
} }
} }
bool IsValid() const { return is_valid_; } bool IsValid() const { return is_valid_; }
private: private:
bool swap_buffers_; bool swap_buffers_;
GdkGLContext* glcontext_; GdkGLContext* glcontext_;
GdkGLDrawable* gldrawable_; GdkGLDrawable* gldrawable_;
bool is_valid_; bool is_valid_;
}; };
} // namespace } // namespace
// static // static
CefRefPtr<OSRWindow> OSRWindow::Create(OSRBrowserProvider* browser_provider, CefRefPtr<OSRWindow> OSRWindow::Create(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView) { CefWindowHandle parentView) {
ASSERT(browser_provider); ASSERT(browser_provider);
if (!browser_provider) if (!browser_provider)
return NULL; return NULL;
return new OSRWindow(browser_provider, transparent, parentView); return new OSRWindow(browser_provider, transparent, parentView);
} }
// static // static
CefRefPtr<OSRWindow> OSRWindow::From( CefRefPtr<OSRWindow> OSRWindow::From(
CefRefPtr<ClientHandler::RenderHandler> renderHandler) { CefRefPtr<ClientHandler::RenderHandler> renderHandler) {
return static_cast<OSRWindow*>(renderHandler.get()); return static_cast<OSRWindow*>(renderHandler.get());
} }
void OSRWindow::OnBeforeClose(CefRefPtr<CefBrowser> browser) { void OSRWindow::OnBeforeClose(CefRefPtr<CefBrowser> browser) {
// Disconnect all signal handlers that reference |this|. // Disconnect all signal handlers that reference |this|.
g_signal_handlers_disconnect_matched(glarea_, G_SIGNAL_MATCH_DATA, 0, 0, g_signal_handlers_disconnect_matched(glarea_, G_SIGNAL_MATCH_DATA, 0, 0,
NULL, NULL, this); NULL, NULL, this);
DisableGL(); DisableGL();
} }
bool OSRWindow::GetViewRect(CefRefPtr<CefBrowser> browser, bool OSRWindow::GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) { CefRect& rect) {
if (!glarea_) if (!glarea_)
return false; return false;
// The simulated screen and view rectangle are the same. This is necessary // The simulated screen and view rectangle are the same. This is necessary
// for popup menus to be located and sized inside the view. // for popup menus to be located and sized inside the view.
rect.x = rect.y = 0; rect.x = rect.y = 0;
rect.width = glarea_->allocation.width; rect.width = glarea_->allocation.width;
rect.height = glarea_->allocation.height; rect.height = glarea_->allocation.height;
return true; return true;
} }
bool OSRWindow::GetScreenPoint(CefRefPtr<CefBrowser> browser, bool OSRWindow::GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX, int viewX,
int viewY, int viewY,
int& screenX, int& screenX,
int& screenY) { int& screenY) {
GdkRectangle screen_rect; GdkRectangle screen_rect;
widget_get_rect_in_screen(glarea_, &screen_rect); widget_get_rect_in_screen(glarea_, &screen_rect);
screenX = screen_rect.x + viewX; screenX = screen_rect.x + viewX;
screenY = screen_rect.y + viewY; screenY = screen_rect.y + viewY;
return true; return true;
} }
void OSRWindow::OnPopupShow(CefRefPtr<CefBrowser> browser, void OSRWindow::OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) { bool show) {
if (!show) { if (!show) {
CefRect dirty_rect = renderer_.popup_rect(); CefRect dirty_rect = renderer_.popup_rect();
renderer_.ClearPopupRects(); renderer_.ClearPopupRects();
browser->GetHost()->Invalidate(dirty_rect, PET_VIEW); browser->GetHost()->Invalidate(dirty_rect, PET_VIEW);
} }
renderer_.OnPopupShow(browser, show); renderer_.OnPopupShow(browser, show);
} }
void OSRWindow::OnPopupSize(CefRefPtr<CefBrowser> browser, void OSRWindow::OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) { const CefRect& rect) {
renderer_.OnPopupSize(browser, rect); renderer_.OnPopupSize(browser, rect);
} }
void OSRWindow::OnPaint(CefRefPtr<CefBrowser> browser, void OSRWindow::OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type, PaintElementType type,
const RectList& dirtyRects, const RectList& dirtyRects,
const void* buffer, const void* buffer,
int width, int height) { int width, int height) {
if (painting_popup_) { if (painting_popup_) {
renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height); renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height);
return; return;
} }
if (!gl_enabled_) if (!gl_enabled_)
EnableGL(); EnableGL();
ScopedGLContext scoped_gl_context(glarea_, true); ScopedGLContext scoped_gl_context(glarea_, true);
if (!scoped_gl_context.IsValid()) if (!scoped_gl_context.IsValid())
return; return;
renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height); renderer_.OnPaint(browser, type, dirtyRects, buffer, width, height);
if (type == PET_VIEW && !renderer_.popup_rect().IsEmpty()) { if (type == PET_VIEW && !renderer_.popup_rect().IsEmpty()) {
painting_popup_ = true; painting_popup_ = true;
CefRect client_popup_rect(0, 0, CefRect client_popup_rect(0, 0,
renderer_.popup_rect().width, renderer_.popup_rect().width,
renderer_.popup_rect().height); renderer_.popup_rect().height);
browser->GetHost()->Invalidate(client_popup_rect, PET_POPUP); browser->GetHost()->Invalidate(client_popup_rect, PET_POPUP);
painting_popup_ = false; painting_popup_ = false;
} }
renderer_.Render(); renderer_.Render();
} }
void OSRWindow::OnCursorChange(CefRefPtr<CefBrowser> browser, void OSRWindow::OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) { CefCursorHandle cursor) {
GtkWidget* window = gtk_widget_get_toplevel(glarea_); GtkWidget* window = gtk_widget_get_toplevel(glarea_);
GdkWindow* gdk_window = gtk_widget_get_window(window); GdkWindow* gdk_window = gtk_widget_get_window(window);
if (cursor->type == GDK_LAST_CURSOR) if (cursor->type == GDK_LAST_CURSOR)
cursor = NULL; cursor = NULL;
gdk_window_set_cursor(gdk_window, cursor); gdk_window_set_cursor(gdk_window, cursor);
} }
void OSRWindow::Invalidate() { void OSRWindow::Invalidate() {
if (!CefCurrentlyOn(TID_UI)) { if (!CefCurrentlyOn(TID_UI)) {
CefPostTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Invalidate)); CefPostTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Invalidate));
return; return;
} }
// Don't post another task if the previous task is still pending. // Don't post another task if the previous task is still pending.
if (render_task_pending_) if (render_task_pending_)
return; return;
render_task_pending_ = true; render_task_pending_ = true;
// Render at 30fps. // Render at 30fps.
static const int kRenderDelay = 1000 / 30; static const int kRenderDelay = 1000 / 30;
CefPostDelayedTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Render), CefPostDelayedTask(TID_UI, NewCefRunnableMethod(this, &OSRWindow::Render),
kRenderDelay); kRenderDelay);
} }
bool OSRWindow::IsOverPopupWidget(int x, int y) const { bool OSRWindow::IsOverPopupWidget(int x, int y) const {
const CefRect& rc = renderer_.popup_rect(); const CefRect& rc = renderer_.popup_rect();
int popup_right = rc.x + rc.width; int popup_right = rc.x + rc.width;
int popup_bottom = rc.y + rc.height; int popup_bottom = rc.y + rc.height;
return (x >= rc.x) && (x < popup_right) && return (x >= rc.x) && (x < popup_right) &&
(y >= rc.y) && (y < popup_bottom); (y >= rc.y) && (y < popup_bottom);
} }
int OSRWindow::GetPopupXOffset() const { int OSRWindow::GetPopupXOffset() const {
return renderer_.original_popup_rect().x - renderer_.popup_rect().x; return renderer_.original_popup_rect().x - renderer_.popup_rect().x;
} }
int OSRWindow::GetPopupYOffset() const { int OSRWindow::GetPopupYOffset() const {
return renderer_.original_popup_rect().y - renderer_.popup_rect().y; return renderer_.original_popup_rect().y - renderer_.popup_rect().y;
} }
void OSRWindow::ApplyPopupOffset(int& x, int& y) const { void OSRWindow::ApplyPopupOffset(int& x, int& y) const {
if (IsOverPopupWidget(x, y)) { if (IsOverPopupWidget(x, y)) {
x += GetPopupXOffset(); x += GetPopupXOffset();
y += GetPopupYOffset(); y += GetPopupYOffset();
} }
} }
OSRWindow::OSRWindow(OSRBrowserProvider* browser_provider, OSRWindow::OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView) CefWindowHandle parentView)
: renderer_(transparent), : renderer_(transparent),
browser_provider_(browser_provider), browser_provider_(browser_provider),
gl_enabled_(false), gl_enabled_(false),
painting_popup_(false), painting_popup_(false),
render_task_pending_(false) { render_task_pending_(false) {
glarea_ = gtk_drawing_area_new(); glarea_ = gtk_drawing_area_new();
ASSERT(glarea_); ASSERT(glarea_);
GdkGLConfig* glconfig = gdk_gl_config_new_by_mode( GdkGLConfig* glconfig = gdk_gl_config_new_by_mode(
static_cast<GdkGLConfigMode>(GDK_GL_MODE_RGB | static_cast<GdkGLConfigMode>(GDK_GL_MODE_RGB |
GDK_GL_MODE_DEPTH | GDK_GL_MODE_DEPTH |
GDK_GL_MODE_DOUBLE)); GDK_GL_MODE_DOUBLE));
ASSERT(glconfig); ASSERT(glconfig);
gtk_widget_set_gl_capability(glarea_, glconfig, NULL, TRUE, gtk_widget_set_gl_capability(glarea_, glconfig, NULL, TRUE,
GDK_GL_RGBA_TYPE); GDK_GL_RGBA_TYPE);
gtk_widget_set_can_focus(glarea_, TRUE); gtk_widget_set_can_focus(glarea_, TRUE);
g_signal_connect(G_OBJECT(glarea_), "size_allocate", g_signal_connect(G_OBJECT(glarea_), "size_allocate",
G_CALLBACK(glarea_size_allocation), this); G_CALLBACK(glarea_size_allocation), this);
gtk_widget_set_events(glarea_, gtk_widget_set_events(glarea_,
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK | GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK | GDK_KEY_RELEASE_MASK |
GDK_ENTER_NOTIFY_MASK | GDK_ENTER_NOTIFY_MASK |
GDK_LEAVE_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK |
GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_MASK |
GDK_POINTER_MOTION_HINT_MASK | GDK_POINTER_MOTION_HINT_MASK |
GDK_SCROLL_MASK | GDK_SCROLL_MASK |
GDK_FOCUS_CHANGE_MASK); GDK_FOCUS_CHANGE_MASK);
g_signal_connect(G_OBJECT(glarea_), "button_press_event", g_signal_connect(G_OBJECT(glarea_), "button_press_event",
G_CALLBACK(glarea_click_event), this); G_CALLBACK(glarea_click_event), this);
g_signal_connect(G_OBJECT(glarea_), "button_release_event", g_signal_connect(G_OBJECT(glarea_), "button_release_event",
G_CALLBACK(glarea_click_event), this); G_CALLBACK(glarea_click_event), this);
g_signal_connect(G_OBJECT(glarea_), "key_press_event", g_signal_connect(G_OBJECT(glarea_), "key_press_event",
G_CALLBACK(glarea_key_event), this); G_CALLBACK(glarea_key_event), this);
g_signal_connect(G_OBJECT(glarea_), "key_release_event", g_signal_connect(G_OBJECT(glarea_), "key_release_event",
G_CALLBACK(glarea_key_event), this); G_CALLBACK(glarea_key_event), this);
g_signal_connect(G_OBJECT(glarea_), "enter_notify_event", g_signal_connect(G_OBJECT(glarea_), "enter_notify_event",
G_CALLBACK(glarea_move_event), this); G_CALLBACK(glarea_move_event), this);
g_signal_connect(G_OBJECT(glarea_), "leave_notify_event", g_signal_connect(G_OBJECT(glarea_), "leave_notify_event",
G_CALLBACK(glarea_move_event), this); G_CALLBACK(glarea_move_event), this);
g_signal_connect(G_OBJECT(glarea_), "motion_notify_event", g_signal_connect(G_OBJECT(glarea_), "motion_notify_event",
G_CALLBACK(glarea_move_event), this); G_CALLBACK(glarea_move_event), this);
g_signal_connect(G_OBJECT(glarea_), "scroll_event", g_signal_connect(G_OBJECT(glarea_), "scroll_event",
G_CALLBACK(glarea_scroll_event), this); G_CALLBACK(glarea_scroll_event), this);
g_signal_connect(G_OBJECT(glarea_), "focus_in_event", g_signal_connect(G_OBJECT(glarea_), "focus_in_event",
G_CALLBACK(glarea_focus_event), this); G_CALLBACK(glarea_focus_event), this);
g_signal_connect(G_OBJECT(glarea_), "focus_out_event", g_signal_connect(G_OBJECT(glarea_), "focus_out_event",
G_CALLBACK(glarea_focus_event), this); G_CALLBACK(glarea_focus_event), this);
gtk_container_add(GTK_CONTAINER(parentView), glarea_); gtk_container_add(GTK_CONTAINER(parentView), glarea_);
} }
OSRWindow::~OSRWindow() { OSRWindow::~OSRWindow() {
} }
void OSRWindow::Render() { void OSRWindow::Render() {
ASSERT(CefCurrentlyOn(TID_UI)); ASSERT(CefCurrentlyOn(TID_UI));
if (render_task_pending_) if (render_task_pending_)
render_task_pending_ = false; render_task_pending_ = false;
if (!gl_enabled_) if (!gl_enabled_)
EnableGL(); EnableGL();
ScopedGLContext scoped_gl_context(glarea_, true); ScopedGLContext scoped_gl_context(glarea_, true);
if (!scoped_gl_context.IsValid()) if (!scoped_gl_context.IsValid())
return; return;
renderer_.Render(); renderer_.Render();
} }
void OSRWindow::EnableGL() { void OSRWindow::EnableGL() {
ASSERT(CefCurrentlyOn(TID_UI)); ASSERT(CefCurrentlyOn(TID_UI));
if (gl_enabled_) if (gl_enabled_)
return; return;
ScopedGLContext scoped_gl_context(glarea_, false); ScopedGLContext scoped_gl_context(glarea_, false);
if (!scoped_gl_context.IsValid()) if (!scoped_gl_context.IsValid())
return; return;
renderer_.Initialize(); renderer_.Initialize();
gl_enabled_ = true; gl_enabled_ = true;
} }
void OSRWindow::DisableGL() { void OSRWindow::DisableGL() {
ASSERT(CefCurrentlyOn(TID_UI)); ASSERT(CefCurrentlyOn(TID_UI));
if (!gl_enabled_) if (!gl_enabled_)
return; return;
ScopedGLContext scoped_gl_context(glarea_, false); ScopedGLContext scoped_gl_context(glarea_, false);
if (!scoped_gl_context.IsValid()) if (!scoped_gl_context.IsValid())
return; return;
renderer_.Cleanup(); renderer_.Cleanup();
gl_enabled_ = false; gl_enabled_ = false;
} }

View File

@ -1,90 +1,90 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_ #ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_ #define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#pragma once #pragma once
#include "include/cef_render_handler.h" #include "include/cef_render_handler.h"
#include "cefclient/client_handler.h" #include "cefclient/client_handler.h"
#include "cefclient/osrenderer.h" #include "cefclient/osrenderer.h"
class OSRBrowserProvider { class OSRBrowserProvider {
public: public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0; virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected: protected:
virtual ~OSRBrowserProvider() {} virtual ~OSRBrowserProvider() {}
}; };
class OSRWindow : public ClientHandler::RenderHandler { class OSRWindow : public ClientHandler::RenderHandler {
public: public:
// Create a new OSRWindow instance. |browser_provider| must outlive this // Create a new OSRWindow instance. |browser_provider| must outlive this
// object. // object.
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider, static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView); CefWindowHandle parentView);
static CefRefPtr<OSRWindow> From( static CefRefPtr<OSRWindow> From(
CefRefPtr<ClientHandler::RenderHandler> renderHandler); CefRefPtr<ClientHandler::RenderHandler> renderHandler);
CefWindowHandle GetWindowHandle() const { CefWindowHandle GetWindowHandle() const {
return glarea_; return glarea_;
} }
CefRefPtr<CefBrowserHost> GetBrowserHost() const { CefRefPtr<CefBrowserHost> GetBrowserHost() const {
return browser_provider_->GetBrowser()->GetHost(); return browser_provider_->GetBrowser()->GetHost();
} }
// ClientHandler::RenderHandler methods // ClientHandler::RenderHandler methods
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE; virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods // CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser, virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE; CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser, virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX, int viewX,
int viewY, int viewY,
int& screenX, int& screenX,
int& screenY) OVERRIDE; int& screenY) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser, virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE; bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser, virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE; const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser, virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type, PaintElementType type,
const RectList& dirtyRects, const RectList& dirtyRects,
const void* buffer, const void* buffer,
int width, int width,
int height) OVERRIDE; int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser, virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE; CefCursorHandle cursor) OVERRIDE;
void Invalidate(); void Invalidate();
bool IsOverPopupWidget(int x, int y) const; bool IsOverPopupWidget(int x, int y) const;
int GetPopupXOffset() const; int GetPopupXOffset() const;
int GetPopupYOffset() const; int GetPopupYOffset() const;
void ApplyPopupOffset(int& x, int& y) const; void ApplyPopupOffset(int& x, int& y) const;
private: private:
OSRWindow(OSRBrowserProvider* browser_provider, OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView); CefWindowHandle parentView);
virtual ~OSRWindow(); virtual ~OSRWindow();
void Render(); void Render();
void EnableGL(); void EnableGL();
void DisableGL(); void DisableGL();
ClientOSRenderer renderer_; ClientOSRenderer renderer_;
OSRBrowserProvider* browser_provider_; OSRBrowserProvider* browser_provider_;
CefWindowHandle glarea_; CefWindowHandle glarea_;
bool gl_enabled_; bool gl_enabled_;
bool painting_popup_; bool painting_popup_;
bool render_task_pending_; bool render_task_pending_;
IMPLEMENT_REFCOUNTING(OSRWindow); IMPLEMENT_REFCOUNTING(OSRWindow);
}; };
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_ #endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_

View File

@ -1,128 +1,128 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license // reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_ #ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_ #define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#include "include/cef_client.h" #include "include/cef_client.h"
#include "cefclient/client_handler.h" #include "cefclient/client_handler.h"
class ClientOSRenderer; class ClientOSRenderer;
class OSRBrowserProvider { class OSRBrowserProvider {
public: public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0; virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected: protected:
virtual ~OSRBrowserProvider() {} virtual ~OSRBrowserProvider() {}
}; };
// The client OpenGL view. // The client OpenGL view.
@interface ClientOpenGLView : NSOpenGLView { @interface ClientOpenGLView : NSOpenGLView {
@public @public
NSTrackingArea* tracking_area_; NSTrackingArea* tracking_area_;
OSRBrowserProvider* browser_provider_; OSRBrowserProvider* browser_provider_;
ClientOSRenderer* renderer_; ClientOSRenderer* renderer_;
NSPoint last_mouse_pos_; NSPoint last_mouse_pos_;
NSPoint cur_mouse_pos_; NSPoint cur_mouse_pos_;
bool rotating_; bool rotating_;
bool was_last_mouse_down_on_view_; bool was_last_mouse_down_on_view_;
// Event monitor for scroll wheel end event. // Event monitor for scroll wheel end event.
id endWheelMonitor_; id endWheelMonitor_;
} }
- (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency; - (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency;
- (NSPoint)getClickPointForEvent:(NSEvent*)event; - (NSPoint)getClickPointForEvent:(NSEvent*)event;
- (void)getKeyEvent:(CefKeyEvent&)keyEvent forEvent:(NSEvent*)event; - (void)getKeyEvent:(CefKeyEvent&)keyEvent forEvent:(NSEvent*)event;
- (void)getMouseEvent:(CefMouseEvent&)mouseEvent forEvent:(NSEvent*)event; - (void)getMouseEvent:(CefMouseEvent&)mouseEvent forEvent:(NSEvent*)event;
- (int)getModifiersForEvent:(NSEvent*)event; - (int)getModifiersForEvent:(NSEvent*)event;
- (BOOL)isKeyUpEvent:(NSEvent*)event; - (BOOL)isKeyUpEvent:(NSEvent*)event;
- (BOOL)isKeyPadEvent:(NSEvent*)event; - (BOOL)isKeyPadEvent:(NSEvent*)event;
- (CefRefPtr<CefBrowser>)getBrowser; - (CefRefPtr<CefBrowser>)getBrowser;
@end @end
// Handler for off-screen rendering windows. // Handler for off-screen rendering windows.
class ClientOSRHandler : public ClientHandler::RenderHandler { class ClientOSRHandler : public ClientHandler::RenderHandler {
public: public:
explicit ClientOSRHandler(ClientOpenGLView* view, explicit ClientOSRHandler(ClientOpenGLView* view,
OSRBrowserProvider* browser_provider); OSRBrowserProvider* browser_provider);
virtual ~ClientOSRHandler(); virtual ~ClientOSRHandler();
void Disconnect(); void Disconnect();
// ClientHandler::RenderHandler // ClientHandler::RenderHandler
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE; virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods // CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser, virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE; CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser, virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX, int viewX,
int viewY, int viewY,
int& screenX, int& screenX,
int& screenY) OVERRIDE; int& screenY) OVERRIDE;
virtual bool GetScreenInfo(CefRefPtr<CefBrowser> browser, virtual bool GetScreenInfo(CefRefPtr<CefBrowser> browser,
CefScreenInfo& screen_info) OVERRIDE; CefScreenInfo& screen_info) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser, virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE; bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser, virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE; const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser, virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type, PaintElementType type,
const RectList& dirtyRects, const RectList& dirtyRects,
const void* buffer, const void* buffer,
int width, int height) OVERRIDE; int width, int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser, virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE; CefCursorHandle cursor) OVERRIDE;
CefWindowHandle view() { return view_; } CefWindowHandle view() { return view_; }
private: private:
void SetLoading(bool isLoading); void SetLoading(bool isLoading);
ClientOpenGLView* view_; ClientOpenGLView* view_;
bool painting_popup_; bool painting_popup_;
// Include the default reference counting implementation. // Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientOSRHandler); IMPLEMENT_REFCOUNTING(ClientOSRHandler);
}; };
class OSRWindow { class OSRWindow {
public: public:
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider, static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView, CefWindowHandle parentView,
const CefRect& frame); const CefRect& frame);
CefRefPtr<ClientHandler::RenderHandler> GetRenderHandler() { CefRefPtr<ClientHandler::RenderHandler> GetRenderHandler() {
return render_client.get(); return render_client.get();
} }
CefWindowHandle GetWindowHandle() { return view_; } CefWindowHandle GetWindowHandle() { return view_; }
private: private:
OSRWindow(OSRBrowserProvider* browser_provider, OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent, bool transparent,
CefWindowHandle parentView, CefWindowHandle parentView,
const CefRect& frame); const CefRect& frame);
~OSRWindow(); ~OSRWindow();
CefRefPtr<ClientOSRHandler> render_client; CefRefPtr<ClientOSRHandler> render_client;
CefWindowHandle view_; CefWindowHandle view_;
IMPLEMENT_REFCOUNTING(OSRWindow); IMPLEMENT_REFCOUNTING(OSRWindow);
}; };
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_ #endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +1,69 @@
<html> <html>
<head><title>OSR Test</title></head> <head><title>OSR Test</title></head>
<style> <style>
.red_hover:hover {color:red;} .red_hover:hover {color:red;}
#li { width: 530px; } #li { width: 530px; }
body {background:rgba(255, 0, 0, 0.5); } body {background:rgba(255, 0, 0, 0.5); }
input {-webkit-appearance: none; } input {-webkit-appearance: none; }
#LI11select {width: 75px;} #LI11select {width: 75px;}
</style> </style>
<script> <script>
function sendBrowserMessage(paramString) { function sendBrowserMessage(paramString) {
app.sendMessage("osrtest", [paramString]); app.sendMessage("osrtest", [paramString]);
} }
function getElement(id) { return document.getElementById(id); } function getElement(id) { return document.getElementById(id); }
function makeH1Red() { getElement('LI00').style.color='red'; } function makeH1Red() { getElement('LI00').style.color='red'; }
function makeH1Black() { getElement('LI00').style.color='black'; } function makeH1Black() { getElement('LI00').style.color='black'; }
function navigate() { location.href='?k='+getElement('editbox').value; } function navigate() { location.href='?k='+getElement('editbox').value; }
function load() { var select = document.getElementById('LI11select'); function load() { var select = document.getElementById('LI11select');
for (var i = 1; i < 21; i++) for (var i = 1; i < 21; i++)
select.options.add(new Option('Option ' + i, i)); select.options.add(new Option('Option ' + i, i));
} }
function onEventTest(event) { function onEventTest(event) {
var param = event.type; var param = event.type;
if (event.type == "click") if (event.type == "click")
param += event.button; param += event.button;
sendBrowserMessage(param); sendBrowserMessage(param);
} }
</script> </script>
<body onfocus='onEventTest(event)' onblur='onEventTest(event)' onload='load();'> <body onfocus='onEventTest(event)' onblur='onEventTest(event)' onload='load();'>
<h1 id='LI00' onclick="onEventTest(event)"> <h1 id='LI00' onclick="onEventTest(event)">
OSR Testing h1 - Focus and blur OSR Testing h1 - Focus and blur
<select id='LI11select'> <select id='LI11select'>
<option value='0'>Default</option> <option value='0'>Default</option>
</select> </select>
this page and will get this red black this page and will get this red black
</h1> </h1>
<ol> <ol>
<li id='LI01'>OnPaint should be called each time a page loads</li> <li id='LI01'>OnPaint should be called each time a page loads</li>
<li id='LI02' style='cursor:pointer;'><span>Move mouse <li id='LI02' style='cursor:pointer;'><span>Move mouse
to require an OnCursorChange call</span></li> to require an OnCursorChange call</span></li>
<li id='LI03' onmousemove="onEventTest(event)"><span>Hover will color this with <li id='LI03' onmousemove="onEventTest(event)"><span>Hover will color this with
red. Will trigger OnPaint once on enter and once on leave</span></li> red. Will trigger OnPaint once on enter and once on leave</span></li>
<li id='LI04'>Right clicking will show contextual menu and will request <li id='LI04'>Right clicking will show contextual menu and will request
GetScreenPoint</li> GetScreenPoint</li>
<li id='LI05'>IsWindowRenderingDisabled should be true</li> <li id='LI05'>IsWindowRenderingDisabled should be true</li>
<li id='LI06'>WasResized should trigger full repaint if size changes. <li id='LI06'>WasResized should trigger full repaint if size changes.
</li> </li>
<li id='LI07'>Invalidate should trigger OnPaint once</li> <li id='LI07'>Invalidate should trigger OnPaint once</li>
<li id='LI08'>Click and write here with SendKeyEvent to trigger repaints: <li id='LI08'>Click and write here with SendKeyEvent to trigger repaints:
<input id='editbox' type='text' value='' size="5"></li> <input id='editbox' type='text' value='' size="5"></li>
<li id='LI09'>Click here with SendMouseClickEvent to navigate: <li id='LI09'>Click here with SendMouseClickEvent to navigate:
<input id='btnnavigate' type='button' onclick='navigate()' <input id='btnnavigate' type='button' onclick='navigate()'
value='Click here to navigate' id='editbox' /></li> value='Click here to navigate' id='editbox' /></li>
<li id='LI10' title='EXPECTED_TOOLTIP'>Mouse over this element will <li id='LI10' title='EXPECTED_TOOLTIP'>Mouse over this element will
trigger show a tooltip</li> trigger show a tooltip</li>
</ol> </ol>
<br /> <br />
<br /> <br />
<br /> <br />
<br /> <br />
<br /> <br />
<br /> <br />
</body> </body>
</html> </html>

View File

@ -1,32 +1,32 @@
<html> <html>
<head> <head>
<title>Other Tests</title> <title>Other Tests</title>
</head> </head>
<body bgcolor="white"> <body bgcolor="white">
<h3>Various other internal and external tests.</h3> <h3>Various other internal and external tests.</h3>
<ul> <ul>
<li><a href="http://mudcu.be/labs/JS1k/BreathingGalaxies.html">Accelerated 2D Canvas</a></li> <li><a href="http://mudcu.be/labs/JS1k/BreathingGalaxies.html">Accelerated 2D Canvas</a></li>
<li><a href="http://webkit.org/blog-files/3d-transforms/poster-circle.html">Accelerated Layers</a></li> <li><a href="http://webkit.org/blog-files/3d-transforms/poster-circle.html">Accelerated Layers</a></li>
<li><a href="http://html5advent2011.digitpaint.nl/3/index.html">Cursors</a></li> <li><a href="http://html5advent2011.digitpaint.nl/3/index.html">Cursors</a></li>
<li><a href="http://tests/dialogs">Dialogs</a></li> <li><a href="http://tests/dialogs">Dialogs</a></li>
<li><a href="http://tests/domaccess">DOM Access</a></li> <li><a href="http://tests/domaccess">DOM Access</a></li>
<li><a href="http://html5demos.com/drag">Drag & Drop</a></li> <li><a href="http://html5demos.com/drag">Drag & Drop</a></li>
<li><a href="http://www.adobe.com/software/flash/about/">Flash Plugin</a></li> <li><a href="http://www.adobe.com/software/flash/about/">Flash Plugin</a></li>
<li><a href="http://html5demos.com/geo">Geolocation</a></li> <li><a href="http://html5demos.com/geo">Geolocation</a></li>
<li><a href="http://www.html5test.com">HTML5 Feature Test</a></li> <li><a href="http://www.html5test.com">HTML5 Feature Test</a></li>
<li><a href="http://www.youtube.com/watch?v=siOHh0uzcuY&html5=True">HTML5 Video</a></li> <li><a href="http://www.youtube.com/watch?v=siOHh0uzcuY&html5=True">HTML5 Video</a></li>
<li><a href="http://tests/binding">JavaScript Binding</a></li> <li><a href="http://tests/binding">JavaScript Binding</a></li>
<li><a href="http://tests/performance">JavaScript Performance Tests</a></li> <li><a href="http://tests/performance">JavaScript Performance Tests</a></li>
<li><a href="http://tests/performance2">JavaScript Performance (2) Tests</a></li> <li><a href="http://tests/performance2">JavaScript Performance (2) Tests</a></li>
<li><a href="http://tests/window">JavaScript Window Manipulation</a></li> <li><a href="http://tests/window">JavaScript Window Manipulation</a></li>
<li><a href="http://tests/localstorage">Local Storage</a></li> <li><a href="http://tests/localstorage">Local Storage</a></li>
<li><a href="http://mrdoob.com/lab/javascript/requestanimationframe/">requestAnimationFrame</a></li> <li><a href="http://mrdoob.com/lab/javascript/requestanimationframe/">requestAnimationFrame</a></li>
<li><a href="client://tests/handler.html">Scheme Handler</a></li> <li><a href="client://tests/handler.html">Scheme Handler</a></li>
<li><a href="http://slides.html5rocks.com/#speech-input">Speech Input</a> - requires "enable-speech-input" flag</li> <li><a href="http://slides.html5rocks.com/#speech-input">Speech Input</a> - requires "enable-speech-input" flag</li>
<li><a href="http://tests/transparency">Transparency</a></li> <li><a href="http://tests/transparency">Transparency</a></li>
<li><a href="http://webglsamples.googlecode.com/hg/field/field.html">WebGL</a></li> <li><a href="http://webglsamples.googlecode.com/hg/field/field.html">WebGL</a></li>
<li><a href="http://apprtc.appspot.com/">WebRTC</a> - requires "enable-media-stream" flag</li> <li><a href="http://apprtc.appspot.com/">WebRTC</a> - requires "enable-media-stream" flag</li>
<li><a href="http://tests/xmlhttprequest">XMLHttpRequest</a></li> <li><a href="http://tests/xmlhttprequest">XMLHttpRequest</a></li>
</ul> </ul>
</body> </body>
</html> </html>

View File

@ -1,442 +1,442 @@
<!DOCTYPE HTML> <!DOCTYPE HTML>
<html> <html>
<head> <head>
<title>Performance Tests (2)</title> <title>Performance Tests (2)</title>
<style> <style>
body { font-family: Tahoma, Serif; font-size: 9pt; } body { font-family: Tahoma, Serif; font-size: 9pt; }
.left { text-align: left; } .left { text-align: left; }
.right { text-align: right; } .right { text-align: right; }
.center { text-align: center; } .center { text-align: center; }
table.resultTable table.resultTable
{ {
border: 1px solid black; border: 1px solid black;
border-collapse: collapse; border-collapse: collapse;
empty-cells: show; empty-cells: show;
width: 100%; width: 100%;
} }
table.resultTable td table.resultTable td
{ {
padding: 2px 4px; padding: 2px 4px;
border: 1px solid black; border: 1px solid black;
} }
table.resultTable > thead > tr table.resultTable > thead > tr
{ {
font-weight: bold; font-weight: bold;
background: lightblue; background: lightblue;
} }
table.resultTable > tbody > tr:nth-child(odd) table.resultTable > tbody > tr:nth-child(odd)
{ {
background: white; background: white;
} }
table.resultTable > tbody > tr:nth-child(even) table.resultTable > tbody > tr:nth-child(even)
{ {
background: lightgray; background: lightgray;
} }
.hide { display: none; } .hide { display: none; }
</style> </style>
</head> </head>
<body bgcolor="white"> <body bgcolor="white">
<h1>Performance Tests (2)</h1> <h1>Performance Tests (2)</h1>
<form id="sForm" onsubmit="runTestSuite();return false"> <form id="sForm" onsubmit="runTestSuite();return false">
<table> <table>
<tr> <tr>
<td colspan="2">Settings:</td> <td colspan="2">Settings:</td>
</tr> </tr>
<tr> <tr>
<td class="right">Iterations:</td> <td class="right">Iterations:</td>
<td><input id="sIterations" type="text" value="1000" required pattern="[0-9]+" /></td> <td><input id="sIterations" type="text" value="1000" required pattern="[0-9]+" /></td>
</tr> </tr>
<tr> <tr>
<td class="right">Samples:</td> <td class="right">Samples:</td>
<td><input id="sSamples" type="text" value="100" required pattern="[0-9]+" /></td> <td><input id="sSamples" type="text" value="100" required pattern="[0-9]+" /></td>
</tr> </tr>
<tr> <tr>
<td class="right">Mode:</td> <td class="right">Mode:</td>
<td><input id="sAsync" name="sMode" type="radio" value="async" checked>Asynchronous</input> <td><input id="sAsync" name="sMode" type="radio" value="async" checked>Asynchronous</input>
<input id="sSync" name="sMode" type="radio" value="sync">Synchronous</input> <input id="sSync" name="sMode" type="radio" value="sync">Synchronous</input>
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"><button type="submit" id="sRun" autofocus>Run!</button></td> <td colspan="2"><button type="submit" id="sRun" autofocus>Run!</button></td>
</tr> </tr>
</table> </table>
</form> </form>
<div><span id="statusBox"></span> <progress id="progressBox" value="0" style="display:none"></progress></div> <div><span id="statusBox"></span> <progress id="progressBox" value="0" style="display:none"></progress></div>
<div style="padding-top:10px; padding-bottom:10px"> <div style="padding-top:10px; padding-bottom:10px">
<table id="resultTable" class="resultTable"> <table id="resultTable" class="resultTable">
<thead> <thead>
<tr> <tr>
<td class="center" style="width:1%">Enabled</td> <td class="center" style="width:1%">Enabled</td>
<td class="center" style="width:10%">Name</td> <td class="center" style="width:10%">Name</td>
<td class="center" style="width:5%">Samples x Iterations</td> <td class="center" style="width:5%">Samples x Iterations</td>
<td class="center" style="width:5%">Min,&nbsp;ms</td> <td class="center" style="width:5%">Min,&nbsp;ms</td>
<td class="center" style="width:5%">Avg,&nbsp;ms</td> <td class="center" style="width:5%">Avg,&nbsp;ms</td>
<td class="center" style="width:5%">Max,&nbsp;ms</td> <td class="center" style="width:5%">Max,&nbsp;ms</td>
<td class="center" style="width:5%">Average calls/sec</td> <td class="center" style="width:5%">Average calls/sec</td>
<td class="center" style="width:5%">Measuring Inacurracy</td> <td class="center" style="width:5%">Measuring Inacurracy</td>
<td class="center hide" style="width:5%">Memory, MB</td> <td class="center hide" style="width:5%">Memory, MB</td>
<td class="center hide" style="width:5%">Memory delta, MB</td> <td class="center hide" style="width:5%">Memory delta, MB</td>
<td class="center" style="width:55%">Description</td> <td class="center" style="width:55%">Description</td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<!-- result rows here --> <!-- result rows here -->
</tbody> </tbody>
</table> </table>
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
(function () { (function () {
function getPrivateWorkingSet() { function getPrivateWorkingSet() {
return 0; // TODO: window.PerfTestGetPrivateWorkingSet(); return 0; // TODO: window.PerfTestGetPrivateWorkingSet();
} }
var disableWarmUp = true; var disableWarmUp = true;
var asyncExecution = true; var asyncExecution = true;
var testIterations = 1000; var testIterations = 1000;
var totalSamples = 100; var totalSamples = 100;
var sampleDelay = 0; var sampleDelay = 0;
var collectSamples = false; var collectSamples = false;
var tests = []; var tests = [];
var testIndex = -1; var testIndex = -1;
function execTestFunc(test) { function execTestFunc(test) {
try { try {
var begin = new Date(); var begin = new Date();
test.func(test.totalIterations); test.func(test.totalIterations);
var end = new Date(); var end = new Date();
return (end - begin); return (end - begin);
} catch (e) { } catch (e) {
test.error = e.toString(); test.error = e.toString();
return 0; return 0;
} }
} }
function execTest(test) { function execTest(test) {
if (disableWarmUp) { test.warmedUp = true; } if (disableWarmUp) { test.warmedUp = true; }
function nextStep() { function nextStep() {
if (asyncExecution) { if (asyncExecution) {
setTimeout(function () { execTest(test); }, sampleDelay); setTimeout(function () { execTest(test); }, sampleDelay);
} else { } else {
execTest(test); execTest(test);
} }
} }
function nextTest() { function nextTest() {
updateStatus(test); updateStatus(test);
appendResult(test); appendResult(test);
return execNextTest(); return execNextTest();
} }
updateStatus(test); updateStatus(test);
if (!test.warmedUp) { if (!test.warmedUp) {
execTestFunc(test); execTestFunc(test);
if (!test.error) { if (!test.error) {
test.warmedUp = true; test.warmedUp = true;
test.beginMemory = getPrivateWorkingSet(); test.beginMemory = getPrivateWorkingSet();
return nextStep(); return nextStep();
} else { } else {
return nextTest(); return nextTest();
} }
} }
if (test.sample >= test.totalSamples) { if (test.sample >= test.totalSamples) {
test.avg = test.total / test.totalSamples; test.avg = test.total / test.totalSamples;
test.endMemory = getPrivateWorkingSet(); test.endMemory = getPrivateWorkingSet();
return nextTest(); return nextTest();
} }
if (test.skipped) return nextTest(); if (test.skipped) return nextTest();
var elapsed = execTestFunc(test); var elapsed = execTestFunc(test);
if (!test.error) { if (!test.error) {
test.total += elapsed; test.total += elapsed;
if (!test.min) test.min = elapsed; if (!test.min) test.min = elapsed;
else if (test.min > elapsed) test.min = elapsed; else if (test.min > elapsed) test.min = elapsed;
if (!test.max) test.max = elapsed; if (!test.max) test.max = elapsed;
else if (test.max < elapsed) test.max = elapsed; else if (test.max < elapsed) test.max = elapsed;
if (collectSamples) { if (collectSamples) {
test.results.push(elapsed); test.results.push(elapsed);
} }
test.sample++; test.sample++;
return nextStep(); return nextStep();
} else { } else {
return nextTest(); return nextTest();
} }
} }
function updateStatus(test) { function updateStatus(test) {
var statusBox = document.getElementById("statusBox"); var statusBox = document.getElementById("statusBox");
var progressBox = document.getElementById("progressBox"); var progressBox = document.getElementById("progressBox");
if (test.skipped || test.error || test.sample >= test.totalSamples) { if (test.skipped || test.error || test.sample >= test.totalSamples) {
statusBox.innerText = ""; statusBox.innerText = "";
progressBox.style.display = "none"; progressBox.style.display = "none";
} else { } else {
statusBox.innerText = (testIndex + 1) + "/" + tests.length + ": " + test.name + " (" + test.sample + "/" + test.totalSamples + ")"; statusBox.innerText = (testIndex + 1) + "/" + tests.length + ": " + test.name + " (" + test.sample + "/" + test.totalSamples + ")";
progressBox.value = (test.sample / test.totalSamples); progressBox.value = (test.sample / test.totalSamples);
progressBox.style.display = "inline"; progressBox.style.display = "inline";
} }
} }
function appendResult(test) { function appendResult(test) {
if (test.name == "warmup") return; if (test.name == "warmup") return;
var id = "testResultRow_" + test.index; var id = "testResultRow_" + test.index;
var nearBound = (test.max - test.avg) < (test.avg - test.min) ? test.max : test.min; var nearBound = (test.max - test.avg) < (test.avg - test.min) ? test.max : test.min;
var memoryDelta = test.endMemory - test.beginMemory; var memoryDelta = test.endMemory - test.beginMemory;
if (memoryDelta < 0) memoryDelta = "-" + Math.abs(memoryDelta).toFixed(2); if (memoryDelta < 0) memoryDelta = "-" + Math.abs(memoryDelta).toFixed(2);
else memoryDelta = "+" + Math.abs(memoryDelta).toFixed(2); else memoryDelta = "+" + Math.abs(memoryDelta).toFixed(2);
var markup = ["<tr id='" + id + "'>", var markup = ["<tr id='" + id + "'>",
"<td class='left'><input type='checkbox' id='test_enabled_", test.index ,"' ", (!test.skipped ? "checked" : "") ," /></td>", "<td class='left'><input type='checkbox' id='test_enabled_", test.index ,"' ", (!test.skipped ? "checked" : "") ," /></td>",
"<td class='left'>", test.name, "</td>", "<td class='left'>", test.name, "</td>",
"<td class='right'>", test.totalSamples, "x", test.totalIterations, "</td>", "<td class='right'>", test.totalSamples, "x", test.totalIterations, "</td>",
"<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.min.toFixed(2), "</td>", "<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.min.toFixed(2), "</td>",
"<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.avg.toFixed(2), "</td>", "<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.avg.toFixed(2), "</td>",
"<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.max.toFixed(2), "</td>", "<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : test.max.toFixed(2), "</td>",
"<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : (test.totalIterations * 1000 / test.avg).toFixed(2), "</td>", "<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : (test.totalIterations * 1000 / test.avg).toFixed(2), "</td>",
"<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : ("&#x00B1; " + (Math.abs(test.avg - nearBound) / (test.avg) * (100)).toFixed(2) + "%"), "</td>", "<td class='right'>", test.skipped || test.error || !test.prepared ? "-" : ("&#x00B1; " + (Math.abs(test.avg - nearBound) / (test.avg) * (100)).toFixed(2) + "%"), "</td>",
"<td class='right hide'>", test.skipped || test.error || !test.prepared ? "-" : test.endMemory.toFixed(2), "</td>", "<td class='right hide'>", test.skipped || test.error || !test.prepared ? "-" : test.endMemory.toFixed(2), "</td>",
"<td class='right hide'>", test.skipped || test.error || !test.prepared ? "-" : memoryDelta, "</td>", "<td class='right hide'>", test.skipped || test.error || !test.prepared ? "-" : memoryDelta, "</td>",
"<td class='left'>", test.description, test.error ? (test.description ? "<br/>" : "") + "<span style='color:red'>" + test.error + "</span>" : "", "</td>", "<td class='left'>", test.description, test.error ? (test.description ? "<br/>" : "") + "<span style='color:red'>" + test.error + "</span>" : "", "</td>",
"</tr>" "</tr>"
].join(""); ].join("");
// test.results.join(", "), "<br/>", // test.results.join(", "), "<br/>",
var row = document.getElementById(id); var row = document.getElementById(id);
if (row) { if (row) {
row.outerHTML = markup; row.outerHTML = markup;
} else { } else {
var tbody = document.getElementById("resultTable").tBodies[0]; var tbody = document.getElementById("resultTable").tBodies[0];
tbody.insertAdjacentHTML("beforeEnd", markup); tbody.insertAdjacentHTML("beforeEnd", markup);
} }
} }
function prepareQueuedTests() { function prepareQueuedTests() {
testIndex = -1; testIndex = -1;
for (var i = 0; i < tests.length; i++) { for (var i = 0; i < tests.length; i++) {
var test = tests[i]; var test = tests[i];
test.index = i; test.index = i;
test.prepared = false; test.prepared = false;
test.warmedUp = false; test.warmedUp = false;
test.sample = 0; test.sample = 0;
test.total = 0; test.total = 0;
test.results = []; test.results = [];
test.error = false; test.error = false;
test.min = null; test.min = null;
test.avg = null; test.avg = null;
test.max = null; test.max = null;
test.beginMemory = null; test.beginMemory = null;
test.endMemory = null; test.endMemory = null;
test.totalIterations = parseInt(testIterations / test.complex); test.totalIterations = parseInt(testIterations / test.complex);
test.totalSamples = parseInt(totalSamples / test.complex); test.totalSamples = parseInt(totalSamples / test.complex);
var skipElement = document.getElementById('test_enabled_' + test.index); var skipElement = document.getElementById('test_enabled_' + test.index);
test.skipped = skipElement ? !skipElement.checked : (test.skipped || false); test.skipped = skipElement ? !skipElement.checked : (test.skipped || false);
if (test.totalIterations <= 0) test.totalIterations = 1; if (test.totalIterations <= 0) test.totalIterations = 1;
if (test.totalSamples <= 0) test.totalSamples = 1; if (test.totalSamples <= 0) test.totalSamples = 1;
appendResult(test); appendResult(test);
test.prepared = true; test.prepared = true;
} }
} }
function queueTest(func, name, description) { function queueTest(func, name, description) {
var test; var test;
if (typeof func === "function") { if (typeof func === "function") {
test = { test = {
name: name, name: name,
func: func, func: func,
description: description description: description
}; };
} else { } else {
test = func; test = func;
} }
test.warmedUp = false; test.warmedUp = false;
test.complex = test.complex || 1; test.complex = test.complex || 1;
tests.push(test); tests.push(test);
} }
function execNextTest() { function execNextTest() {
testIndex++; testIndex++;
if (tests.length <= testIndex) { if (tests.length <= testIndex) {
return testSuiteFinished(); return testSuiteFinished();
} else { } else {
return execTest(tests[testIndex]); return execTest(tests[testIndex]);
} }
} }
function execQueuedTests() { function execQueuedTests() {
prepareQueuedTests(); prepareQueuedTests();
execNextTest(); execNextTest();
} }
function setSettingsState(disabled) { function setSettingsState(disabled) {
document.getElementById('sIterations').disabled = disabled; document.getElementById('sIterations').disabled = disabled;
document.getElementById('sSamples').disabled = disabled; document.getElementById('sSamples').disabled = disabled;
document.getElementById('sAsync').disabled = disabled; document.getElementById('sAsync').disabled = disabled;
document.getElementById('sSync').disabled = disabled; document.getElementById('sSync').disabled = disabled;
document.getElementById('sRun').disabled = disabled; document.getElementById('sRun').disabled = disabled;
} }
function testSuiteFinished() { function testSuiteFinished() {
setSettingsState(false); setSettingsState(false);
} }
window.runTestSuite = function () { window.runTestSuite = function () {
setSettingsState(true); setSettingsState(true);
testIterations = parseInt(document.getElementById('sIterations').value); testIterations = parseInt(document.getElementById('sIterations').value);
totalSamples = parseInt(document.getElementById('sSamples').value); totalSamples = parseInt(document.getElementById('sSamples').value);
asyncExecution = document.getElementById('sAsync').checked; asyncExecution = document.getElementById('sAsync').checked;
setTimeout(execQueuedTests, 0); setTimeout(execQueuedTests, 0);
} }
setTimeout(prepareQueuedTests, 0); setTimeout(prepareQueuedTests, 0);
// Test queue. // Test queue.
queueTest({ queueTest({
name: "PerfTestReturnValue Default", name: "PerfTestReturnValue Default",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(); window.PerfTestReturnValue();
} }
}, },
description: "No arguments, returns int32 value.", description: "No arguments, returns int32 value.",
skipped: true, skipped: true,
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (0, Undefined)", name: "PerfTestReturnValue (0, Undefined)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(0); window.PerfTestReturnValue(0);
} }
}, },
description: "Int argument, returns undefined value." description: "Int argument, returns undefined value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (1, Null)", name: "PerfTestReturnValue (1, Null)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(1); window.PerfTestReturnValue(1);
} }
}, },
description: "Int argument, returns null value." description: "Int argument, returns null value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (2, Bool)", name: "PerfTestReturnValue (2, Bool)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(2); window.PerfTestReturnValue(2);
} }
}, },
description: "Int argument, returns bool value." description: "Int argument, returns bool value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (3, Int)", name: "PerfTestReturnValue (3, Int)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(3); window.PerfTestReturnValue(3);
} }
}, },
description: "Int argument, returns int value." description: "Int argument, returns int value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (4, UInt)", name: "PerfTestReturnValue (4, UInt)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(4); window.PerfTestReturnValue(4);
} }
}, },
description: "Int argument, returns uint value." description: "Int argument, returns uint value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (5, Double)", name: "PerfTestReturnValue (5, Double)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(5); window.PerfTestReturnValue(5);
} }
}, },
description: "Int argument, returns double value." description: "Int argument, returns double value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (6, Date)", name: "PerfTestReturnValue (6, Date)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(6); window.PerfTestReturnValue(6);
} }
}, },
description: "Int argument, returns date value.", description: "Int argument, returns date value.",
skipped: true, skipped: true,
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (7, String)", name: "PerfTestReturnValue (7, String)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(7); window.PerfTestReturnValue(7);
} }
}, },
description: "Int argument, returns string value." description: "Int argument, returns string value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (8, Object)", name: "PerfTestReturnValue (8, Object)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(8); window.PerfTestReturnValue(8);
} }
}, },
description: "Int argument, returns object value." description: "Int argument, returns object value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (9, Array)", name: "PerfTestReturnValue (9, Array)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(9); window.PerfTestReturnValue(9);
} }
}, },
description: "Int argument, returns array value." description: "Int argument, returns array value."
}); });
queueTest({ queueTest({
name: "PerfTestReturnValue (10, Function)", name: "PerfTestReturnValue (10, Function)",
func: function (count) { func: function (count) {
for (var i = 0; i < count; i++) { for (var i = 0; i < count; i++) {
window.PerfTestReturnValue(10); window.PerfTestReturnValue(10);
} }
}, },
description: "Int argument, returns function value.", description: "Int argument, returns function value.",
skipped: true, skipped: true,
}); });
// add more tests to queueTest // add more tests to queueTest
})(); })();
</script> </script>
</body> </body>
</html> </html>

View File

@ -1,78 +1,78 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#include "cefclient/window_test.h" #include "cefclient/window_test.h"
namespace window_test { namespace window_test {
namespace { namespace {
// Toggles the current display state. // Toggles the current display state.
void Toggle(CefWindowHandle handle, UINT nCmdShow) { void Toggle(CefWindowHandle handle, UINT nCmdShow) {
HWND root_wnd = ::GetAncestor(handle, GA_ROOT); HWND root_wnd = ::GetAncestor(handle, GA_ROOT);
// Retrieve current window placement information. // Retrieve current window placement information.
WINDOWPLACEMENT placement; WINDOWPLACEMENT placement;
::GetWindowPlacement(root_wnd, &placement); ::GetWindowPlacement(root_wnd, &placement);
if (placement.showCmd == nCmdShow) if (placement.showCmd == nCmdShow)
::ShowWindow(root_wnd, SW_RESTORE); ::ShowWindow(root_wnd, SW_RESTORE);
else else
::ShowWindow(root_wnd, nCmdShow); ::ShowWindow(root_wnd, nCmdShow);
} }
} // namespace } // namespace
void SetPos(CefWindowHandle handle, int x, int y, int width, int height) { void SetPos(CefWindowHandle handle, int x, int y, int width, int height) {
HWND root_wnd = ::GetAncestor(handle, GA_ROOT); HWND root_wnd = ::GetAncestor(handle, GA_ROOT);
// Retrieve current window placement information. // Retrieve current window placement information.
WINDOWPLACEMENT placement; WINDOWPLACEMENT placement;
::GetWindowPlacement(root_wnd, &placement); ::GetWindowPlacement(root_wnd, &placement);
// Retrieve information about the display that contains the window. // Retrieve information about the display that contains the window.
HMONITOR monitor = MonitorFromRect(&placement.rcNormalPosition, HMONITOR monitor = MonitorFromRect(&placement.rcNormalPosition,
MONITOR_DEFAULTTONEAREST); MONITOR_DEFAULTTONEAREST);
MONITORINFO info; MONITORINFO info;
info.cbSize = sizeof(info); info.cbSize = sizeof(info);
GetMonitorInfo(monitor, &info); GetMonitorInfo(monitor, &info);
// Make sure the window is inside the display. // Make sure the window is inside the display.
CefRect display_rect( CefRect display_rect(
info.rcWork.left, info.rcWork.left,
info.rcWork.top, info.rcWork.top,
info.rcWork.right - info.rcWork.left, info.rcWork.right - info.rcWork.left,
info.rcWork.bottom - info.rcWork.top); info.rcWork.bottom - info.rcWork.top);
CefRect window_rect(x, y, width, height); CefRect window_rect(x, y, width, height);
ModifyBounds(display_rect, window_rect); ModifyBounds(display_rect, window_rect);
if (placement.showCmd == SW_MINIMIZE || placement.showCmd == SW_MAXIMIZE) { if (placement.showCmd == SW_MINIMIZE || placement.showCmd == SW_MAXIMIZE) {
// The window is currently minimized or maximized. Restore it to the desired // The window is currently minimized or maximized. Restore it to the desired
// position. // position.
placement.rcNormalPosition.left = window_rect.x; placement.rcNormalPosition.left = window_rect.x;
placement.rcNormalPosition.right = window_rect.x + window_rect.width; placement.rcNormalPosition.right = window_rect.x + window_rect.width;
placement.rcNormalPosition.top = window_rect.y; placement.rcNormalPosition.top = window_rect.y;
placement.rcNormalPosition.bottom = window_rect.y + window_rect.height; placement.rcNormalPosition.bottom = window_rect.y + window_rect.height;
::SetWindowPlacement(root_wnd, &placement); ::SetWindowPlacement(root_wnd, &placement);
::ShowWindow(root_wnd, SW_RESTORE); ::ShowWindow(root_wnd, SW_RESTORE);
} else { } else {
// Set the window position. // Set the window position.
::SetWindowPos(root_wnd, NULL, window_rect.x, window_rect.y, ::SetWindowPos(root_wnd, NULL, window_rect.x, window_rect.y,
window_rect.width, window_rect.height, SWP_NOZORDER); window_rect.width, window_rect.height, SWP_NOZORDER);
} }
} }
void Minimize(CefWindowHandle handle) { void Minimize(CefWindowHandle handle) {
Toggle(handle, SW_MINIMIZE); Toggle(handle, SW_MINIMIZE);
} }
void Maximize(CefWindowHandle handle) { void Maximize(CefWindowHandle handle) {
Toggle(handle, SW_MAXIMIZE); Toggle(handle, SW_MAXIMIZE);
} }
void Restore(CefWindowHandle handle) { void Restore(CefWindowHandle handle) {
::ShowWindow(::GetAncestor(handle, GA_ROOT), SW_RESTORE); ::ShowWindow(::GetAncestor(handle, GA_ROOT), SW_RESTORE);
} }
} // namespace window_test } // namespace window_test

View File

@ -1,262 +1,262 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#include "include/cef_scheme.h" #include "include/cef_scheme.h"
#include "base/file_util.h" #include "base/file_util.h"
#include "base/files/scoped_temp_dir.h" #include "base/files/scoped_temp_dir.h"
#include "tests/unittests/test_handler.h" #include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
namespace { namespace {
const char kTestDomain[] = "test-download"; const char kTestDomain[] = "test-download";
const char kTestEntryUrl[] = "http://test-download/test.html"; const char kTestEntryUrl[] = "http://test-download/test.html";
const char kTestDownloadUrl[] = "http://test-download/download.txt"; const char kTestDownloadUrl[] = "http://test-download/download.txt";
const char kTestFileName[] = "download_test.txt"; const char kTestFileName[] = "download_test.txt";
const char kTestContentDisposition[] = const char kTestContentDisposition[] =
"attachment; filename=\"download_test.txt\""; "attachment; filename=\"download_test.txt\"";
const char kTestMimeType[] = "text/plain"; const char kTestMimeType[] = "text/plain";
const char kTestContent[] = "Download test text"; const char kTestContent[] = "Download test text";
class DownloadSchemeHandler : public CefResourceHandler { class DownloadSchemeHandler : public CefResourceHandler {
public: public:
explicit DownloadSchemeHandler(TrackCallback* got_download_request) explicit DownloadSchemeHandler(TrackCallback* got_download_request)
: got_download_request_(got_download_request), : got_download_request_(got_download_request),
offset_(0) {} offset_(0) {}
virtual bool ProcessRequest(CefRefPtr<CefRequest> request, virtual bool ProcessRequest(CefRefPtr<CefRequest> request,
CefRefPtr<CefCallback> callback) CefRefPtr<CefCallback> callback)
OVERRIDE { OVERRIDE {
std::string url = request->GetURL(); std::string url = request->GetURL();
if (url == kTestEntryUrl) { if (url == kTestEntryUrl) {
content_ = "<html><body>Download Test</body></html>"; content_ = "<html><body>Download Test</body></html>";
mime_type_ = "text/html"; mime_type_ = "text/html";
} else if (url == kTestDownloadUrl) { } else if (url == kTestDownloadUrl) {
got_download_request_->yes(); got_download_request_->yes();
content_ = kTestContent; content_ = kTestContent;
mime_type_ = kTestMimeType; mime_type_ = kTestMimeType;
content_disposition_ = kTestContentDisposition; content_disposition_ = kTestContentDisposition;
} else { } else {
EXPECT_TRUE(false); // Not reached. EXPECT_TRUE(false); // Not reached.
return false; return false;
} }
callback->Continue(); callback->Continue();
return true; return true;
} }
virtual void GetResponseHeaders(CefRefPtr<CefResponse> response, virtual void GetResponseHeaders(CefRefPtr<CefResponse> response,
int64& response_length, int64& response_length,
CefString& redirectUrl) OVERRIDE { CefString& redirectUrl) OVERRIDE {
response_length = content_.size(); response_length = content_.size();
response->SetStatus(200); response->SetStatus(200);
response->SetMimeType(mime_type_); response->SetMimeType(mime_type_);
if (!content_disposition_.empty()) { if (!content_disposition_.empty()) {
CefResponse::HeaderMap headerMap; CefResponse::HeaderMap headerMap;
response->GetHeaderMap(headerMap); response->GetHeaderMap(headerMap);
headerMap.insert( headerMap.insert(
std::make_pair("Content-Disposition", content_disposition_)); std::make_pair("Content-Disposition", content_disposition_));
response->SetHeaderMap(headerMap); response->SetHeaderMap(headerMap);
} }
} }
virtual bool ReadResponse(void* data_out, virtual bool ReadResponse(void* data_out,
int bytes_to_read, int bytes_to_read,
int& bytes_read, int& bytes_read,
CefRefPtr<CefCallback> callback) CefRefPtr<CefCallback> callback)
OVERRIDE { OVERRIDE {
bool has_data = false; bool has_data = false;
bytes_read = 0; bytes_read = 0;
size_t size = content_.size(); size_t size = content_.size();
if (offset_ < size) { if (offset_ < size) {
int transfer_size = int transfer_size =
std::min(bytes_to_read, static_cast<int>(size - offset_)); std::min(bytes_to_read, static_cast<int>(size - offset_));
memcpy(data_out, content_.c_str() + offset_, transfer_size); memcpy(data_out, content_.c_str() + offset_, transfer_size);
offset_ += transfer_size; offset_ += transfer_size;
bytes_read = transfer_size; bytes_read = transfer_size;
has_data = true; has_data = true;
} }
return has_data; return has_data;
} }
virtual void Cancel() OVERRIDE { virtual void Cancel() OVERRIDE {
} }
private: private:
TrackCallback* got_download_request_; TrackCallback* got_download_request_;
std::string content_; std::string content_;
std::string mime_type_; std::string mime_type_;
std::string content_disposition_; std::string content_disposition_;
size_t offset_; size_t offset_;
IMPLEMENT_REFCOUNTING(SchemeHandler); IMPLEMENT_REFCOUNTING(SchemeHandler);
}; };
class DownloadSchemeHandlerFactory : public CefSchemeHandlerFactory { class DownloadSchemeHandlerFactory : public CefSchemeHandlerFactory {
public: public:
explicit DownloadSchemeHandlerFactory(TrackCallback* got_download_request) explicit DownloadSchemeHandlerFactory(TrackCallback* got_download_request)
: got_download_request_(got_download_request) {} : got_download_request_(got_download_request) {}
virtual CefRefPtr<CefResourceHandler> Create( virtual CefRefPtr<CefResourceHandler> Create(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefFrame> frame,
const CefString& scheme_name, const CefString& scheme_name,
CefRefPtr<CefRequest> request) OVERRIDE { CefRefPtr<CefRequest> request) OVERRIDE {
return new DownloadSchemeHandler(got_download_request_); return new DownloadSchemeHandler(got_download_request_);
} }
private: private:
TrackCallback* got_download_request_; TrackCallback* got_download_request_;
IMPLEMENT_REFCOUNTING(SchemeHandlerFactory); IMPLEMENT_REFCOUNTING(SchemeHandlerFactory);
}; };
class DownloadTestHandler : public TestHandler { class DownloadTestHandler : public TestHandler {
public: public:
DownloadTestHandler() {} DownloadTestHandler() {}
virtual void RunTest() OVERRIDE { virtual void RunTest() OVERRIDE {
CefRegisterSchemeHandlerFactory("http", kTestDomain, CefRegisterSchemeHandlerFactory("http", kTestDomain,
new DownloadSchemeHandlerFactory(&got_download_request_)); new DownloadSchemeHandlerFactory(&got_download_request_));
// Create a new temporary directory. // Create a new temporary directory.
EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
test_path_ = temp_dir_.path().AppendASCII(kTestFileName); test_path_ = temp_dir_.path().AppendASCII(kTestFileName);
// Create the browser // Create the browser
CreateBrowser(kTestEntryUrl); CreateBrowser(kTestEntryUrl);
} }
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE { int httpStatusCode) OVERRIDE {
EXPECT_STREQ(kTestEntryUrl, frame->GetURL().ToString().c_str()); EXPECT_STREQ(kTestEntryUrl, frame->GetURL().ToString().c_str());
// Begin the download. // Begin the download.
browser->GetHost()->StartDownload(kTestDownloadUrl); browser->GetHost()->StartDownload(kTestDownloadUrl);
} }
virtual void OnBeforeDownload( virtual void OnBeforeDownload(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDownloadItem> download_item, CefRefPtr<CefDownloadItem> download_item,
const CefString& suggested_name, const CefString& suggested_name,
CefRefPtr<CefBeforeDownloadCallback> callback) OVERRIDE { CefRefPtr<CefBeforeDownloadCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_TRUE(CefCurrentlyOn(TID_UI));
EXPECT_FALSE(got_on_before_download_); EXPECT_FALSE(got_on_before_download_);
got_on_before_download_.yes(); got_on_before_download_.yes();
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
EXPECT_STREQ(kTestFileName, suggested_name.ToString().c_str()); EXPECT_STREQ(kTestFileName, suggested_name.ToString().c_str());
EXPECT_TRUE(download_item.get()); EXPECT_TRUE(download_item.get());
EXPECT_TRUE(callback.get()); EXPECT_TRUE(callback.get());
download_id_ = download_item->GetId(); download_id_ = download_item->GetId();
EXPECT_LT(0U, download_id_); EXPECT_LT(0U, download_id_);
EXPECT_TRUE(download_item->IsValid()); EXPECT_TRUE(download_item->IsValid());
EXPECT_TRUE(download_item->IsInProgress()); EXPECT_TRUE(download_item->IsInProgress());
EXPECT_FALSE(download_item->IsComplete()); EXPECT_FALSE(download_item->IsComplete());
EXPECT_FALSE(download_item->IsCanceled()); EXPECT_FALSE(download_item->IsCanceled());
EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1),
download_item->GetTotalBytes()); download_item->GetTotalBytes());
EXPECT_EQ(0UL, download_item->GetFullPath().length()); EXPECT_EQ(0UL, download_item->GetFullPath().length());
EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str());
EXPECT_EQ(0UL, download_item->GetSuggestedFileName().length()); EXPECT_EQ(0UL, download_item->GetSuggestedFileName().length());
EXPECT_STREQ(kTestContentDisposition, EXPECT_STREQ(kTestContentDisposition,
download_item->GetContentDisposition().ToString().c_str()); download_item->GetContentDisposition().ToString().c_str());
EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str());
callback->Continue(test_path_.value(), false); callback->Continue(test_path_.value(), false);
} }
virtual void OnDownloadUpdated( virtual void OnDownloadUpdated(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefBrowser> browser,
CefRefPtr<CefDownloadItem> download_item, CefRefPtr<CefDownloadItem> download_item,
CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE { CefRefPtr<CefDownloadItemCallback> callback) OVERRIDE {
EXPECT_TRUE(CefCurrentlyOn(TID_UI)); EXPECT_TRUE(CefCurrentlyOn(TID_UI));
got_on_download_updated_.yes(); got_on_download_updated_.yes();
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
EXPECT_TRUE(download_item.get()); EXPECT_TRUE(download_item.get());
EXPECT_TRUE(callback.get()); EXPECT_TRUE(callback.get());
if (got_on_before_download_) if (got_on_before_download_)
EXPECT_EQ(download_id_, download_item->GetId()); EXPECT_EQ(download_id_, download_item->GetId());
EXPECT_LE(0LL, download_item->GetCurrentSpeed()); EXPECT_LE(0LL, download_item->GetCurrentSpeed());
EXPECT_LE(0, download_item->GetPercentComplete()); EXPECT_LE(0, download_item->GetPercentComplete());
EXPECT_TRUE(download_item->IsValid()); EXPECT_TRUE(download_item->IsValid());
EXPECT_FALSE(download_item->IsCanceled()); EXPECT_FALSE(download_item->IsCanceled());
EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str());
EXPECT_STREQ(kTestContentDisposition, EXPECT_STREQ(kTestContentDisposition,
download_item->GetContentDisposition().ToString().c_str()); download_item->GetContentDisposition().ToString().c_str());
EXPECT_STREQ(kTestMimeType, EXPECT_STREQ(kTestMimeType,
download_item->GetMimeType().ToString().c_str()); download_item->GetMimeType().ToString().c_str());
std::string full_path = download_item->GetFullPath(); std::string full_path = download_item->GetFullPath();
if (!full_path.empty()) { if (!full_path.empty()) {
got_full_path_.yes(); got_full_path_.yes();
EXPECT_STREQ(CefString(test_path_.value()).ToString().c_str(), EXPECT_STREQ(CefString(test_path_.value()).ToString().c_str(),
full_path.c_str()); full_path.c_str());
} }
if (download_item->IsComplete()) { if (download_item->IsComplete()) {
EXPECT_FALSE(download_item->IsInProgress()); EXPECT_FALSE(download_item->IsInProgress());
EXPECT_EQ(100, download_item->GetPercentComplete()); EXPECT_EQ(100, download_item->GetPercentComplete());
EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1),
download_item->GetReceivedBytes()); download_item->GetReceivedBytes());
EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1), EXPECT_EQ(static_cast<int64>(sizeof(kTestContent)-1),
download_item->GetTotalBytes()); download_item->GetTotalBytes());
DestroyTest(); DestroyTest();
} else { } else {
EXPECT_TRUE(download_item->IsInProgress()); EXPECT_TRUE(download_item->IsInProgress());
EXPECT_LE(0LL, download_item->GetReceivedBytes()); EXPECT_LE(0LL, download_item->GetReceivedBytes());
} }
} }
virtual void DestroyTest() OVERRIDE { virtual void DestroyTest() OVERRIDE {
CefRegisterSchemeHandlerFactory("http", kTestDomain, NULL); CefRegisterSchemeHandlerFactory("http", kTestDomain, NULL);
EXPECT_TRUE(got_download_request_); EXPECT_TRUE(got_download_request_);
EXPECT_TRUE(got_on_before_download_); EXPECT_TRUE(got_on_before_download_);
EXPECT_TRUE(got_on_download_updated_); EXPECT_TRUE(got_on_download_updated_);
EXPECT_TRUE(got_full_path_); EXPECT_TRUE(got_full_path_);
// Verify the file contents. // Verify the file contents.
std::string contents; std::string contents;
EXPECT_TRUE(base::ReadFileToString(test_path_, &contents)); EXPECT_TRUE(base::ReadFileToString(test_path_, &contents));
EXPECT_STREQ(kTestContent, contents.c_str()); EXPECT_STREQ(kTestContent, contents.c_str());
EXPECT_TRUE(temp_dir_.Delete()); EXPECT_TRUE(temp_dir_.Delete());
TestHandler::DestroyTest(); TestHandler::DestroyTest();
} }
private: private:
base::ScopedTempDir temp_dir_; base::ScopedTempDir temp_dir_;
base::FilePath test_path_; base::FilePath test_path_;
uint32 download_id_; uint32 download_id_;
TrackCallback got_download_request_; TrackCallback got_download_request_;
TrackCallback got_on_before_download_; TrackCallback got_on_before_download_;
TrackCallback got_on_download_updated_; TrackCallback got_on_download_updated_;
TrackCallback got_full_path_; TrackCallback got_full_path_;
}; };
} // namespace } // namespace
// Verify that downloads work. // Verify that downloads work.
TEST(DownloadTest, Download) { TEST(DownloadTest, Download) {
CefRefPtr<DownloadTestHandler> handler = new DownloadTestHandler(); CefRefPtr<DownloadTestHandler> handler = new DownloadTestHandler();
handler->ExecuteTest(); handler->ExecuteTest();
} }

View File

@ -1,306 +1,306 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that // reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file. // can be found in the LICENSE file.
#include "include/cef_runnable.h" #include "include/cef_runnable.h"
#include "tests/unittests/test_handler.h" #include "tests/unittests/test_handler.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
namespace { namespace {
const char kLifeSpanUrl[] = "http://tests-life-span/test.html"; const char kLifeSpanUrl[] = "http://tests-life-span/test.html";
const char kUnloadDialogText[] = "Are you sure?"; const char kUnloadDialogText[] = "Are you sure?";
const char kUnloadMsg[] = "LifeSpanTestHandler.Unload"; const char kUnloadMsg[] = "LifeSpanTestHandler.Unload";
// Browser side. // Browser side.
class LifeSpanTestHandler : public TestHandler { class LifeSpanTestHandler : public TestHandler {
public: public:
struct Settings { struct Settings {
Settings() Settings()
: force_close(false), : force_close(false),
add_onunload_handler(false), add_onunload_handler(false),
allow_do_close(true), allow_do_close(true),
accept_before_unload_dialog(true) {} accept_before_unload_dialog(true) {}
bool force_close; bool force_close;
bool add_onunload_handler; bool add_onunload_handler;
bool allow_do_close; bool allow_do_close;
bool accept_before_unload_dialog; bool accept_before_unload_dialog;
}; };
explicit LifeSpanTestHandler(const Settings& settings) explicit LifeSpanTestHandler(const Settings& settings)
: settings_(settings), : settings_(settings),
executing_delay_close_(false) {} executing_delay_close_(false) {}
virtual void RunTest() OVERRIDE { virtual void RunTest() OVERRIDE {
// Add the resources that we will navigate to/from. // Add the resources that we will navigate to/from.
std::string page = "<html><script>"; std::string page = "<html><script>";
page += "window.onunload = function() { app.sendMessage('" + page += "window.onunload = function() { app.sendMessage('" +
std::string(kUnloadMsg) + "'); };"; std::string(kUnloadMsg) + "'); };";
if (settings_.add_onunload_handler) { if (settings_.add_onunload_handler) {
page += "window.onbeforeunload = function() { return '" + page += "window.onbeforeunload = function() { return '" +
std::string(kUnloadDialogText) + "'; };"; std::string(kUnloadDialogText) + "'; };";
} }
page += "</script><body>Page</body></html>"; page += "</script><body>Page</body></html>";
AddResource(kLifeSpanUrl, page, "text/html"); AddResource(kLifeSpanUrl, page, "text/html");
// Create the browser. // Create the browser.
CreateBrowser(kLifeSpanUrl); CreateBrowser(kLifeSpanUrl);
} }
virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE { virtual void OnAfterCreated(CefRefPtr<CefBrowser> browser) OVERRIDE {
got_after_created_.yes(); got_after_created_.yes();
TestHandler::OnAfterCreated(browser); TestHandler::OnAfterCreated(browser);
} }
virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE { virtual bool DoClose(CefRefPtr<CefBrowser> browser) OVERRIDE {
if (executing_delay_close_) if (executing_delay_close_)
return false; return false;
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
got_do_close_.yes(); got_do_close_.yes();
if (!settings_.allow_do_close) { if (!settings_.allow_do_close) {
// The close will be canceled. // The close will be canceled.
ScheduleDelayClose(); ScheduleDelayClose();
} }
return !settings_.allow_do_close; return !settings_.allow_do_close;
} }
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE { virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE {
if (!executing_delay_close_) { if (!executing_delay_close_) {
got_before_close_.yes(); got_before_close_.yes();
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
} }
TestHandler::OnBeforeClose(browser); TestHandler::OnBeforeClose(browser);
} }
virtual bool OnBeforeUnloadDialog( virtual bool OnBeforeUnloadDialog(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefBrowser> browser,
const CefString& message_text, const CefString& message_text,
bool is_reload, bool is_reload,
CefRefPtr<CefJSDialogCallback> callback) OVERRIDE { CefRefPtr<CefJSDialogCallback> callback) OVERRIDE {
if (executing_delay_close_) { if (executing_delay_close_) {
callback->Continue(true, CefString()); callback->Continue(true, CefString());
return true; return true;
} }
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
EXPECT_STREQ(kUnloadDialogText, message_text.ToString().c_str()); EXPECT_STREQ(kUnloadDialogText, message_text.ToString().c_str());
EXPECT_FALSE(is_reload); EXPECT_FALSE(is_reload);
EXPECT_TRUE(callback.get()); EXPECT_TRUE(callback.get());
if (!settings_.accept_before_unload_dialog) { if (!settings_.accept_before_unload_dialog) {
// The close will be canceled. // The close will be canceled.
ScheduleDelayClose(); ScheduleDelayClose();
} }
got_before_unload_dialog_.yes(); got_before_unload_dialog_.yes();
callback->Continue(settings_.accept_before_unload_dialog, CefString()); callback->Continue(settings_.accept_before_unload_dialog, CefString());
return true; return true;
} }
virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser, virtual void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame, CefRefPtr<CefFrame> frame,
int httpStatusCode) OVERRIDE { int httpStatusCode) OVERRIDE {
got_load_end_.yes(); got_load_end_.yes();
EXPECT_TRUE(browser->IsSame(GetBrowser())); EXPECT_TRUE(browser->IsSame(GetBrowser()));
// Attempt to close the browser. // Attempt to close the browser.
browser->GetHost()->CloseBrowser(settings_.force_close); browser->GetHost()->CloseBrowser(settings_.force_close);
} }
virtual bool OnProcessMessageReceived( virtual bool OnProcessMessageReceived(
CefRefPtr<CefBrowser> browser, CefRefPtr<CefBrowser> browser,
CefProcessId source_process, CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE { CefRefPtr<CefProcessMessage> message) OVERRIDE {
const std::string& message_name = message->GetName(); const std::string& message_name = message->GetName();
if (message_name == kUnloadMsg) { if (message_name == kUnloadMsg) {
if (!executing_delay_close_) if (!executing_delay_close_)
got_unload_message_.yes(); got_unload_message_.yes();
return true; return true;
} }
return false; return false;
} }
TrackCallback got_after_created_; TrackCallback got_after_created_;
TrackCallback got_do_close_; TrackCallback got_do_close_;
TrackCallback got_before_close_; TrackCallback got_before_close_;
TrackCallback got_before_unload_dialog_; TrackCallback got_before_unload_dialog_;
TrackCallback got_unload_message_; TrackCallback got_unload_message_;
TrackCallback got_load_end_; TrackCallback got_load_end_;
TrackCallback got_delay_close_; TrackCallback got_delay_close_;
private: private:
// Wait a bit to make sure no additional events are received and then close // Wait a bit to make sure no additional events are received and then close
// the window. // the window.
void ScheduleDelayClose() { void ScheduleDelayClose() {
CefPostDelayedTask(TID_UI, CefPostDelayedTask(TID_UI,
NewCefRunnableMethod(this, &LifeSpanTestHandler::DelayClose), 100); NewCefRunnableMethod(this, &LifeSpanTestHandler::DelayClose), 100);
} }
void DelayClose() { void DelayClose() {
got_delay_close_.yes(); got_delay_close_.yes();
executing_delay_close_ = true; executing_delay_close_ = true;
DestroyTest(); DestroyTest();
} }
Settings settings_; Settings settings_;
// Forces the window to close (bypasses test conditions). // Forces the window to close (bypasses test conditions).
bool executing_delay_close_; bool executing_delay_close_;
}; };
} // namespace } // namespace
TEST(LifeSpanTest, DoCloseAllow) { TEST(LifeSpanTest, DoCloseAllow) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = true; settings.allow_do_close = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_TRUE(handler->got_before_close_); EXPECT_TRUE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_FALSE(handler->got_delay_close_); EXPECT_FALSE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseAllowForce) { TEST(LifeSpanTest, DoCloseAllowForce) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = true; settings.allow_do_close = true;
settings.force_close = true; settings.force_close = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_TRUE(handler->got_before_close_); EXPECT_TRUE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_FALSE(handler->got_delay_close_); EXPECT_FALSE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseDisallow) { TEST(LifeSpanTest, DoCloseDisallow) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = false; settings.allow_do_close = false;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_FALSE(handler->got_before_close_); EXPECT_FALSE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_TRUE(handler->got_delay_close_); EXPECT_TRUE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseDisallowForce) { TEST(LifeSpanTest, DoCloseDisallowForce) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = false; settings.allow_do_close = false;
settings.force_close = true; settings.force_close = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_FALSE(handler->got_before_close_); EXPECT_FALSE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_TRUE(handler->got_delay_close_); EXPECT_TRUE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseDisallowWithOnUnloadAllow) { TEST(LifeSpanTest, DoCloseDisallowWithOnUnloadAllow) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = false; settings.allow_do_close = false;
settings.add_onunload_handler = true; settings.add_onunload_handler = true;
settings.accept_before_unload_dialog = true; settings.accept_before_unload_dialog = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_FALSE(handler->got_before_close_); EXPECT_FALSE(handler->got_before_close_);
EXPECT_TRUE(handler->got_before_unload_dialog_); EXPECT_TRUE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_TRUE(handler->got_delay_close_); EXPECT_TRUE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseAllowWithOnUnloadForce) { TEST(LifeSpanTest, DoCloseAllowWithOnUnloadForce) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = true; settings.allow_do_close = true;
settings.add_onunload_handler = true; settings.add_onunload_handler = true;
settings.force_close = true; settings.force_close = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_TRUE(handler->got_before_close_); EXPECT_TRUE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_FALSE(handler->got_delay_close_); EXPECT_FALSE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, DoCloseDisallowWithOnUnloadForce) { TEST(LifeSpanTest, DoCloseDisallowWithOnUnloadForce) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.allow_do_close = false; settings.allow_do_close = false;
settings.add_onunload_handler = true; settings.add_onunload_handler = true;
settings.force_close = true; settings.force_close = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_FALSE(handler->got_before_close_); EXPECT_FALSE(handler->got_before_close_);
EXPECT_FALSE(handler->got_before_unload_dialog_); EXPECT_FALSE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_TRUE(handler->got_delay_close_); EXPECT_TRUE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, OnUnloadAllow) { TEST(LifeSpanTest, OnUnloadAllow) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.add_onunload_handler = true; settings.add_onunload_handler = true;
settings.accept_before_unload_dialog = true; settings.accept_before_unload_dialog = true;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_TRUE(handler->got_do_close_); EXPECT_TRUE(handler->got_do_close_);
EXPECT_TRUE(handler->got_before_close_); EXPECT_TRUE(handler->got_before_close_);
EXPECT_TRUE(handler->got_before_unload_dialog_); EXPECT_TRUE(handler->got_before_unload_dialog_);
EXPECT_TRUE(handler->got_unload_message_); EXPECT_TRUE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_FALSE(handler->got_delay_close_); EXPECT_FALSE(handler->got_delay_close_);
} }
TEST(LifeSpanTest, OnUnloadDisallow) { TEST(LifeSpanTest, OnUnloadDisallow) {
LifeSpanTestHandler::Settings settings; LifeSpanTestHandler::Settings settings;
settings.add_onunload_handler = true; settings.add_onunload_handler = true;
settings.accept_before_unload_dialog = false; settings.accept_before_unload_dialog = false;
CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings); CefRefPtr<LifeSpanTestHandler> handler = new LifeSpanTestHandler(settings);
handler->ExecuteTest(); handler->ExecuteTest();
EXPECT_TRUE(handler->got_after_created_); EXPECT_TRUE(handler->got_after_created_);
EXPECT_FALSE(handler->got_do_close_); EXPECT_FALSE(handler->got_do_close_);
EXPECT_FALSE(handler->got_before_close_); EXPECT_FALSE(handler->got_before_close_);
EXPECT_TRUE(handler->got_before_unload_dialog_); EXPECT_TRUE(handler->got_before_unload_dialog_);
EXPECT_FALSE(handler->got_unload_message_); EXPECT_FALSE(handler->got_unload_message_);
EXPECT_TRUE(handler->got_load_end_); EXPECT_TRUE(handler->got_load_end_);
EXPECT_TRUE(handler->got_delay_close_); EXPECT_TRUE(handler->got_delay_close_);
} }

View File

@ -1,18 +1,18 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license // reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
#ifndef CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_ #ifndef CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_
#define CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_ #define CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_
#include "include/cef_base.h" #include "include/cef_base.h"
#include "ui/events/keycodes/keyboard_codes.h" #include "ui/events/keycodes/keyboard_codes.h"
namespace osr_unittests { namespace osr_unittests {
CefWindowHandle GetFakeView(); CefWindowHandle GetFakeView();
void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers); void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers);
} // namespace osr_unittests } // namespace osr_unittests
#endif #endif

View File

@ -1,39 +1,39 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license // reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
#import <AppKit/AppKit.h> #import <AppKit/AppKit.h>
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#include "os_rendering_unittest_mac.h" #include "os_rendering_unittest_mac.h"
#include "ui/events/keycodes/keyboard_code_conversion_mac.h" #include "ui/events/keycodes/keyboard_code_conversion_mac.h"
#include "include/cef_base.h" #include "include/cef_base.h"
namespace osr_unittests { namespace osr_unittests {
CefWindowHandle GetFakeView() { CefWindowHandle GetFakeView() {
NSScreen *mainScreen = [NSScreen mainScreen]; NSScreen *mainScreen = [NSScreen mainScreen];
NSRect screenRect = [mainScreen visibleFrame]; NSRect screenRect = [mainScreen visibleFrame];
NSView* fakeView = [[NSView alloc] initWithFrame: screenRect]; NSView* fakeView = [[NSView alloc] initWithFrame: screenRect];
return fakeView; return fakeView;
} }
void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers) { void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers) {
unichar character; unichar character;
unichar unmodified_character; unichar unmodified_character;
// TODO(port): translate modifiers from the input format to NSFlags // TODO(port): translate modifiers from the input format to NSFlags
// MacKeyCodeForWindowsKeyCode takes a NSUinteger as flags. // MacKeyCodeForWindowsKeyCode takes a NSUinteger as flags.
int macKeyCode = ui::MacKeyCodeForWindowsKeyCode(keyCode, int macKeyCode = ui::MacKeyCodeForWindowsKeyCode(keyCode,
modifiers, modifiers,
&character, &character,
&unmodified_character); &unmodified_character);
event.native_key_code = macKeyCode; event.native_key_code = macKeyCode;
event.character = character; event.character = character;
event.unmodified_character = unmodified_character; event.unmodified_character = unmodified_character;
} }
} // namespace osr_unittests } // namespace osr_unittests

View File

@ -1,246 +1,246 @@
# Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights # Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that # reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file. # can be found in the LICENSE file.
from file_util import * from file_util import *
import os import os
import re import re
import shutil import shutil
import string import string
import sys import sys
import textwrap import textwrap
import time import time
import itertools import itertools
import hashlib import hashlib
class cef_api_hash: class cef_api_hash:
""" CEF API hash calculator """ """ CEF API hash calculator """
def __init__(self, headerdir, debugdir = None, verbose = False): def __init__(self, headerdir, debugdir = None, verbose = False):
if headerdir is None or len(headerdir) == 0: if headerdir is None or len(headerdir) == 0:
raise AssertionError("headerdir is not specified") raise AssertionError("headerdir is not specified")
self.__headerdir = headerdir; self.__headerdir = headerdir;
self.__debugdir = debugdir; self.__debugdir = debugdir;
self.__verbose = verbose; self.__verbose = verbose;
self.__debug_enabled = not (self.__debugdir is None) and len(self.__debugdir) > 0; self.__debug_enabled = not (self.__debugdir is None) and len(self.__debugdir) > 0;
self.platforms = [ "windows", "macosx", "linux" ]; self.platforms = [ "windows", "macosx", "linux" ];
self.platform_files = { self.platform_files = {
"windows": [ "windows": [
"internal/cef_types_win.h" "internal/cef_types_win.h"
], ],
"macosx": [ "macosx": [
"internal/cef_types_mac.h", "internal/cef_types_mac.h",
], ],
"linux": [ "linux": [
"internal/cef_types_linux.h" "internal/cef_types_linux.h"
] ]
}; };
self.included_files = [ self.included_files = [
"cef_trace_event.h" "cef_trace_event.h"
]; ];
self.excluded_files = [ self.excluded_files = [
"cef_version.h", "cef_version.h",
"internal/cef_tuple.h", "internal/cef_tuple.h",
"internal/cef_types_wrappers.h", "internal/cef_types_wrappers.h",
"internal/cef_string_wrappers.h", "internal/cef_string_wrappers.h",
"internal/cef_win.h", "internal/cef_win.h",
"internal/cef_mac.h", "internal/cef_mac.h",
"internal/cef_linux.h", "internal/cef_linux.h",
]; ];
def calculate(self): def calculate(self):
filenames = [filename for filename in self.__get_filenames() if not filename in self.excluded_files] filenames = [filename for filename in self.__get_filenames() if not filename in self.excluded_files]
objects = [] objects = []
for filename in filenames: for filename in filenames:
if self.__verbose: if self.__verbose:
print "Processing " + filename + "..." print "Processing " + filename + "..."
content = read_file(os.path.join(self.__headerdir, filename), True) content = read_file(os.path.join(self.__headerdir, filename), True)
platforms = list([p for p in self.platforms if self.__is_platform_filename(filename, p)]) platforms = list([p for p in self.platforms if self.__is_platform_filename(filename, p)])
# Parse cef_string.h happens in special case: grab only defined CEF_STRING_TYPE_xxx declaration # Parse cef_string.h happens in special case: grab only defined CEF_STRING_TYPE_xxx declaration
content_objects = None content_objects = None
if filename == "internal/cef_string.h": if filename == "internal/cef_string.h":
content_objects = self.__parse_string_type(content) content_objects = self.__parse_string_type(content)
else: else:
content_objects = self.__parse_objects(content) content_objects = self.__parse_objects(content)
for o in content_objects: for o in content_objects:
o["text"] = self.__prepare_text(o["text"]) o["text"] = self.__prepare_text(o["text"])
o["platforms"] = platforms o["platforms"] = platforms
o["filename"] = filename o["filename"] = filename
objects.append(o) objects.append(o)
# objects will be sorted including filename, to make stable universal hashes # objects will be sorted including filename, to make stable universal hashes
objects = sorted(objects, key = lambda o: o["name"] + "@" + o["filename"]) objects = sorted(objects, key = lambda o: o["name"] + "@" + o["filename"])
if self.__debug_enabled: if self.__debug_enabled:
namelen = max([len(o["name"]) for o in objects]) namelen = max([len(o["name"]) for o in objects])
filenamelen = max([len(o["filename"]) for o in objects]) filenamelen = max([len(o["filename"]) for o in objects])
dumpsig = []; dumpsig = [];
for o in objects: for o in objects:
dumpsig.append(format(o["name"], str(namelen) + "s") + "|" + format(o["filename"], "" + str(filenamelen) + "s") + "|" + o["text"]); dumpsig.append(format(o["name"], str(namelen) + "s") + "|" + format(o["filename"], "" + str(filenamelen) + "s") + "|" + o["text"]);
self.__write_debug_file("objects.txt", dumpsig) self.__write_debug_file("objects.txt", dumpsig)
revisions = { }; revisions = { };
for platform in itertools.chain(["universal"], self.platforms): for platform in itertools.chain(["universal"], self.platforms):
sig = self.__get_final_sig(objects, platform) sig = self.__get_final_sig(objects, platform)
if self.__debug_enabled: if self.__debug_enabled:
self.__write_debug_file(platform + ".sig", sig) self.__write_debug_file(platform + ".sig", sig)
rev = hashlib.sha1(sig).digest(); rev = hashlib.sha1(sig).digest();
revstr = ''.join(format(ord(i),'0>2x') for i in rev) revstr = ''.join(format(ord(i),'0>2x') for i in rev)
revisions[platform] = revstr revisions[platform] = revstr
return revisions return revisions
def __parse_objects(self, content): def __parse_objects(self, content):
""" Returns array of objects in content file. """ """ Returns array of objects in content file. """
objects = [] objects = []
content = re.sub("//.*\n", "", content) content = re.sub("//.*\n", "", content)
# function declarations # function declarations
for m in re.finditer("\nCEF_EXPORT\s+?.*?\s+?(\w+)\s*?\(.*?\)\s*?;", content, flags = re.DOTALL): for m in re.finditer("\nCEF_EXPORT\s+?.*?\s+?(\w+)\s*?\(.*?\)\s*?;", content, flags = re.DOTALL):
object = { object = {
"name": m.group(1), "name": m.group(1),
"text": m.group(0).strip() "text": m.group(0).strip()
} }
objects.append(object) objects.append(object)
# structs # structs
for m in re.finditer("\ntypedef\s+?struct\s+?(\w+)\s+?\{.*?\}\s+?(\w+)\s*?;", content, flags = re.DOTALL): for m in re.finditer("\ntypedef\s+?struct\s+?(\w+)\s+?\{.*?\}\s+?(\w+)\s*?;", content, flags = re.DOTALL):
object = { object = {
"name": m.group(2), "name": m.group(2),
"text": m.group(0).strip() "text": m.group(0).strip()
} }
objects.append(object) objects.append(object)
# enums # enums
for m in re.finditer("\nenum\s+?(\w+)\s+?\{.*?\}\s*?;", content, flags = re.DOTALL): for m in re.finditer("\nenum\s+?(\w+)\s+?\{.*?\}\s*?;", content, flags = re.DOTALL):
object = { object = {
"name": m.group(1), "name": m.group(1),
"text": m.group(0).strip() "text": m.group(0).strip()
} }
objects.append(object) objects.append(object)
# typedefs # typedefs
for m in re.finditer("\ntypedef\s+?.*?\s+(\w+);", content, flags = 0): for m in re.finditer("\ntypedef\s+?.*?\s+(\w+);", content, flags = 0):
object = { object = {
"name": m.group(1), "name": m.group(1),
"text": m.group(0).strip() "text": m.group(0).strip()
} }
objects.append(object) objects.append(object)
return objects return objects
def __parse_string_type(self, content): def __parse_string_type(self, content):
""" Grab defined CEF_STRING_TYPE_xxx """ """ Grab defined CEF_STRING_TYPE_xxx """
objects = [] objects = []
for m in re.finditer("\n\s*?#\s*?define\s+?(CEF_STRING_TYPE_\w+)\s+?.*?\n", content, flags = 0): for m in re.finditer("\n\s*?#\s*?define\s+?(CEF_STRING_TYPE_\w+)\s+?.*?\n", content, flags = 0):
object = { object = {
"name": m.group(1), "name": m.group(1),
"text": m.group(0), "text": m.group(0),
} }
objects.append(object) objects.append(object)
return objects return objects
def __prepare_text(self, text): def __prepare_text(self, text):
text = text.strip() text = text.strip()
text = re.sub("\s+", " ", text); text = re.sub("\s+", " ", text);
text = re.sub("\(\s+", "(", text); text = re.sub("\(\s+", "(", text);
return text return text
def __get_final_sig(self, objects, platform): def __get_final_sig(self, objects, platform):
sig = [] sig = []
for o in objects: for o in objects:
if platform == "universal" or platform in o["platforms"]: if platform == "universal" or platform in o["platforms"]:
sig.append(o["text"]) sig.append(o["text"])
return "\n".join(sig) return "\n".join(sig)
def __get_filenames(self): def __get_filenames(self):
""" Returns file names to be processed, relative to headerdir """ """ Returns file names to be processed, relative to headerdir """
headers = [os.path.join(self.__headerdir, filename) for filename in self.included_files]; headers = [os.path.join(self.__headerdir, filename) for filename in self.included_files];
headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "capi", "*.h"))) headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "capi", "*.h")))
headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "internal", "*.h"))) headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "internal", "*.h")))
for v in self.platform_files.values(): for v in self.platform_files.values():
headers = itertools.chain(headers, [os.path.join(self.__headerdir, f) for f in v]) headers = itertools.chain(headers, [os.path.join(self.__headerdir, f) for f in v])
normalized = [os.path.relpath(filename, self.__headerdir) for filename in headers]; normalized = [os.path.relpath(filename, self.__headerdir) for filename in headers];
normalized = [f.replace('\\', '/').lower() for f in normalized]; normalized = [f.replace('\\', '/').lower() for f in normalized];
return list(set(normalized)); return list(set(normalized));
def __is_platform_filename(self, filename, platform): def __is_platform_filename(self, filename, platform):
if platform == "universal": if platform == "universal":
return True return True
if not platform in self.platform_files: if not platform in self.platform_files:
return False return False
listed = False listed = False
for p in self.platforms: for p in self.platforms:
if filename in self.platform_files[p]: if filename in self.platform_files[p]:
if p == platform: if p == platform:
return True return True
else: else:
listed = True listed = True
return not listed return not listed
def __write_debug_file(self, filename, content): def __write_debug_file(self, filename, content):
make_dir(self.__debugdir); make_dir(self.__debugdir);
outfile = os.path.join(self.__debugdir, filename); outfile = os.path.join(self.__debugdir, filename);
dir = os.path.dirname(outfile); dir = os.path.dirname(outfile);
make_dir(dir); make_dir(dir);
if not isinstance(content, basestring): if not isinstance(content, basestring):
content = "\n".join(content) content = "\n".join(content)
write_file(outfile, content) write_file(outfile, content)
if __name__ == "__main__": if __name__ == "__main__":
from optparse import OptionParser from optparse import OptionParser
import time import time
disc = """ disc = """
This utility calculates CEF API hash. This utility calculates CEF API hash.
""" """
parser = OptionParser(description=disc) parser = OptionParser(description=disc)
parser.add_option('--cpp-header-dir', dest='cppheaderdir', metavar='DIR', parser.add_option('--cpp-header-dir', dest='cppheaderdir', metavar='DIR',
help='input directory for C++ header files [required]') help='input directory for C++ header files [required]')
parser.add_option('--debug-dir', dest='debugdir', metavar='DIR', parser.add_option('--debug-dir', dest='debugdir', metavar='DIR',
help='intermediate directory for easy debugging') help='intermediate directory for easy debugging')
parser.add_option('-v', '--verbose', parser.add_option('-v', '--verbose',
action='store_true', dest='verbose', default=False, action='store_true', dest='verbose', default=False,
help='output detailed status information') help='output detailed status information')
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
# the cppheader option is required # the cppheader option is required
if options.cppheaderdir is None: if options.cppheaderdir is None:
parser.print_help(sys.stdout) parser.print_help(sys.stdout)
sys.exit() sys.exit()
# calculate # calculate
c_start_time = time.time() c_start_time = time.time()
calc = cef_api_hash(options.cppheaderdir, options.debugdir, options.verbose); calc = cef_api_hash(options.cppheaderdir, options.debugdir, options.verbose);
revisions = calc.calculate(); revisions = calc.calculate();
c_completed_in = time.time() - c_start_time c_completed_in = time.time() - c_start_time
print "{" print "{"
for k in sorted(revisions.keys()): for k in sorted(revisions.keys()):
print format("\"" + k + "\"", ">12s") + ": \"" + revisions[k] + "\"" print format("\"" + k + "\"", ">12s") + ": \"" + revisions[k] + "\""
print "}" print "}"
# print # print
# print 'Completed in: ' + str(c_completed_in) # print 'Completed in: ' + str(c_completed_in)
# print # print
# print "Press any key to continue..."; # print "Press any key to continue...";
# sys.stdin.readline(); # sys.stdin.readline();

View File

@ -1,13 +1,13 @@
# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights # Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that # reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file. # can be found in the LICENSE file.
import datetime import datetime
def get_year(): def get_year():
""" Returns the current year. """ """ Returns the current year. """
return str(datetime.datetime.now().year) return str(datetime.datetime.now().year)
def get_date(): def get_date():
""" Returns the current date. """ """ Returns the current date. """
return datetime.datetime.now().strftime('%B %d, %Y') return datetime.datetime.now().strftime('%B %d, %Y')

File diff suppressed because it is too large Load Diff

View File

@ -1,70 +1,70 @@
# Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights # Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
# reserved. Use of this source code is governed by a BSD-style license that # reserved. Use of this source code is governed by a BSD-style license that
# can be found in the LICENSE file. # can be found in the LICENSE file.
import os import os
import sys import sys
import subprocess import subprocess
import urllib import urllib
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
def check_url(url): def check_url(url):
""" Check the URL and raise an exception if invalid. """ """ Check the URL and raise an exception if invalid. """
if ':' in url[:7]: if ':' in url[:7]:
parts = url.split(':', 1) parts = url.split(':', 1)
if (parts[0] == 'http' or parts[0] == 'https' or parts[0] == 'svn') and \ if (parts[0] == 'http' or parts[0] == 'https' or parts[0] == 'svn') and \
parts[1] == urllib.quote(parts[1]): parts[1] == urllib.quote(parts[1]):
return url return url
sys.stderr.write('Invalid URL: '+url+"\n") sys.stderr.write('Invalid URL: '+url+"\n")
raise Exception('Invalid URL: '+url) raise Exception('Invalid URL: '+url)
def get_svn_info(path): def get_svn_info(path):
""" Retrieves the URL and revision from svn info. """ """ Retrieves the URL and revision from svn info. """
url = 'None' url = 'None'
rev = 'None' rev = 'None'
if path[0:4] == 'http' or os.path.exists(path): if path[0:4] == 'http' or os.path.exists(path):
try: try:
if sys.platform == 'win32': if sys.platform == 'win32':
# Force use of the SVN version bundled with depot_tools. # Force use of the SVN version bundled with depot_tools.
svn = 'svn.bat' svn = 'svn.bat'
else: else:
svn = 'svn' svn = 'svn'
p = subprocess.Popen([svn, 'info', '--xml', path], \ p = subprocess.Popen([svn, 'info', '--xml', path], \
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() out, err = p.communicate()
if err == '': if err == '':
tree = ET.ElementTree(ET.fromstring(out)) tree = ET.ElementTree(ET.fromstring(out))
entry = tree.getroot().find('entry') entry = tree.getroot().find('entry')
url = entry.find('url').text url = entry.find('url').text
rev = entry.attrib['revision'] rev = entry.attrib['revision']
else: else:
raise Exception("Failed to execute svn info:\n"+err+"\n") raise Exception("Failed to execute svn info:\n"+err+"\n")
except IOError, (errno, strerror): except IOError, (errno, strerror):
sys.stderr.write('Failed to read svn info: '+strerror+"\n") sys.stderr.write('Failed to read svn info: '+strerror+"\n")
raise raise
except: except:
raise raise
return {'url': url, 'revision': rev} return {'url': url, 'revision': rev}
def get_revision(path = '.'): def get_revision(path = '.'):
""" Retrieves the revision from svn info. """ """ Retrieves the revision from svn info. """
info = get_svn_info(path) info = get_svn_info(path)
if info['revision'] == 'None': if info['revision'] == 'None':
raise Exception('Unable to retrieve SVN revision for "'+path+'"') raise Exception('Unable to retrieve SVN revision for "'+path+'"')
return info['revision'] return info['revision']
def get_changed_files(path = '.'): def get_changed_files(path = '.'):
""" Retrieves the list of changed files from svn status. """ """ Retrieves the list of changed files from svn status. """
files = [] files = []
if os.path.exists(path): if os.path.exists(path):
try: try:
stream = os.popen('svn status '+path) stream = os.popen('svn status '+path)
for line in stream: for line in stream:
status = line[0] status = line[0]
# Return paths with add, modify and switch status. # Return paths with add, modify and switch status.
if status == 'A' or status == 'M' or status == 'S': if status == 'A' or status == 'M' or status == 'S':
files.append(line[8:].strip()) files.append(line[8:].strip())
except IOError, (errno, strerror): except IOError, (errno, strerror):
sys.stderr.write('Failed to read svn status: '+strerror+"\n") sys.stderr.write('Failed to read svn status: '+strerror+"\n")
raise raise
return files return files