Fix svn:eol-style property.

git-svn-id: https://chromiumembedded.googlecode.com/svn/branches/1453@1473 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
This commit is contained in:
Marshall Greenblatt 2013-10-18 16:59:40 +00:00
parent c384a19748
commit 7ab98f71da
29 changed files with 4230 additions and 4230 deletions

View File

@ -1,136 +1,136 @@
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_
#define CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "include/capi/cef_base_capi.h"
///
// Structure used to represent drag data. The functions of this structure may be
// called on any thread.
///
typedef struct _cef_drag_data_t {
///
// Base structure.
///
cef_base_t base;
///
// Returns true (1) if the drag data is a link.
///
int (CEF_CALLBACK *is_link)(struct _cef_drag_data_t* self);
///
// Returns true (1) if the drag data is a text or html fragment.
///
int (CEF_CALLBACK *is_fragment)(struct _cef_drag_data_t* self);
///
// Returns true (1) if the drag data is a file.
///
int (CEF_CALLBACK *is_file)(struct _cef_drag_data_t* self);
///
// Return the link URL that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_url)(
struct _cef_drag_data_t* self);
///
// Return the title associated with the link being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_title)(
struct _cef_drag_data_t* self);
///
// Return the metadata, if any, associated with the link being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_metadata)(
struct _cef_drag_data_t* self);
///
// Return the plain text fragment that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_text)(
struct _cef_drag_data_t* self);
///
// Return the text/html fragment that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_html)(
struct _cef_drag_data_t* self);
///
// Return the base URL that the fragment came from. This value is used for
// resolving relative URLs and may be NULL.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_base_url)(
struct _cef_drag_data_t* self);
///
// Return the name of the file being dragged out of the browser window.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_file_name)(
struct _cef_drag_data_t* self);
///
// Retrieve the list of file names that are being dragged into the browser
// window.
///
int (CEF_CALLBACK *get_file_names)(struct _cef_drag_data_t* self,
cef_string_list_t names);
} cef_drag_data_t;
#ifdef __cplusplus
}
#endif
#endif // CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_
#define CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "include/capi/cef_base_capi.h"
///
// Structure used to represent drag data. The functions of this structure may be
// called on any thread.
///
typedef struct _cef_drag_data_t {
///
// Base structure.
///
cef_base_t base;
///
// Returns true (1) if the drag data is a link.
///
int (CEF_CALLBACK *is_link)(struct _cef_drag_data_t* self);
///
// Returns true (1) if the drag data is a text or html fragment.
///
int (CEF_CALLBACK *is_fragment)(struct _cef_drag_data_t* self);
///
// Returns true (1) if the drag data is a file.
///
int (CEF_CALLBACK *is_file)(struct _cef_drag_data_t* self);
///
// Return the link URL that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_url)(
struct _cef_drag_data_t* self);
///
// Return the title associated with the link being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_title)(
struct _cef_drag_data_t* self);
///
// Return the metadata, if any, associated with the link being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_link_metadata)(
struct _cef_drag_data_t* self);
///
// Return the plain text fragment that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_text)(
struct _cef_drag_data_t* self);
///
// Return the text/html fragment that is being dragged.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_html)(
struct _cef_drag_data_t* self);
///
// Return the base URL that the fragment came from. This value is used for
// resolving relative URLs and may be NULL.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_fragment_base_url)(
struct _cef_drag_data_t* self);
///
// Return the name of the file being dragged out of the browser window.
///
// The resulting string must be freed by calling cef_string_userfree_free().
cef_string_userfree_t (CEF_CALLBACK *get_file_name)(
struct _cef_drag_data_t* self);
///
// Retrieve the list of file names that are being dragged into the browser
// window.
///
int (CEF_CALLBACK *get_file_names)(struct _cef_drag_data_t* self,
cef_string_list_t names);
} cef_drag_data_t;
#ifdef __cplusplus
}
#endif
#endif // CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_

View File

@ -1,74 +1,74 @@
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_
#define CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "include/capi/cef_base_capi.h"
///
// Implement this structure to handle events related to dragging. The functions
// of this structure will be called on the UI thread.
///
typedef struct _cef_drag_handler_t {
///
// Base structure.
///
cef_base_t base;
///
// Called when an external drag event enters the browser window. |dragData|
// contains the drag event data and |mask| represents the type of drag
// operation. Return false (0) for default drag handling behavior or true (1)
// to cancel the drag event.
///
int (CEF_CALLBACK *on_drag_enter)(struct _cef_drag_handler_t* self,
struct _cef_browser_t* browser, struct _cef_drag_data_t* dragData,
enum cef_drag_operations_mask_t mask);
} cef_drag_handler_t;
#ifdef __cplusplus
}
#endif
#endif // CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_
// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the name Chromium Embedded
// Framework nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool and should not edited
// by hand. See the translator.README.txt file in the tools directory for
// more information.
//
#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_
#define CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "include/capi/cef_base_capi.h"
///
// Implement this structure to handle events related to dragging. The functions
// of this structure will be called on the UI thread.
///
typedef struct _cef_drag_handler_t {
///
// Base structure.
///
cef_base_t base;
///
// Called when an external drag event enters the browser window. |dragData|
// contains the drag event data and |mask| represents the type of drag
// operation. Return false (0) for default drag handling behavior or true (1)
// to cancel the drag event.
///
int (CEF_CALLBACK *on_drag_enter)(struct _cef_drag_handler_t* self,
struct _cef_browser_t* browser, struct _cef_drag_data_t* dragData,
enum cef_drag_operations_mask_t mask);
} cef_drag_handler_t;
#ifdef __cplusplus
}
#endif
#endif // CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_

View File

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

View File

@ -1,217 +1,217 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/media_capture_devices_dispatcher.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/media_devices_monitor.h"
#include "content/public/common/media_stream_request.h"
using content::BrowserThread;
using content::MediaStreamDevices;
namespace {
const content::MediaStreamDevice* FindDefaultDeviceWithId(
const content::MediaStreamDevices& devices,
const std::string& device_id) {
if (devices.empty())
return NULL;
content::MediaStreamDevices::const_iterator iter = devices.begin();
for (; iter != devices.end(); ++iter) {
if (iter->id == device_id) {
return &(*iter);
}
}
return &(*devices.begin());
};
} // namespace
CefMediaCaptureDevicesDispatcher*
CefMediaCaptureDevicesDispatcher::GetInstance() {
return Singleton<CefMediaCaptureDevicesDispatcher>::get();
}
CefMediaCaptureDevicesDispatcher::CefMediaCaptureDevicesDispatcher()
: devices_enumerated_(false) {}
CefMediaCaptureDevicesDispatcher::~CefMediaCaptureDevicesDispatcher() {}
void CefMediaCaptureDevicesDispatcher::RegisterPrefs(
PrefRegistrySimple* registry) {
registry->RegisterStringPref(prefs::kDefaultAudioCaptureDevice,
std::string());
registry->RegisterStringPref(prefs::kDefaultVideoCaptureDevice,
std::string());
}
void CefMediaCaptureDevicesDispatcher::AddObserver(Observer* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!observers_.HasObserver(observer))
observers_.AddObserver(observer);
}
void CefMediaCaptureDevicesDispatcher::RemoveObserver(Observer* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observers_.RemoveObserver(observer);
}
const MediaStreamDevices&
CefMediaCaptureDevicesDispatcher::GetAudioCaptureDevices() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!devices_enumerated_) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&content::EnsureMonitorCaptureDevices));
devices_enumerated_ = true;
}
return audio_devices_;
}
const MediaStreamDevices&
CefMediaCaptureDevicesDispatcher::GetVideoCaptureDevices() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!devices_enumerated_) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&content::EnsureMonitorCaptureDevices));
devices_enumerated_ = true;
}
return video_devices_;
}
void CefMediaCaptureDevicesDispatcher::GetDefaultDevices(
PrefService* prefs,
bool audio,
bool video,
content::MediaStreamDevices* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(audio || video);
std::string default_device;
if (audio) {
default_device = prefs->GetString(prefs::kDefaultAudioCaptureDevice);
GetRequestedDevice(default_device, true, false, devices);
}
if (video) {
default_device = prefs->GetString(prefs::kDefaultVideoCaptureDevice);
GetRequestedDevice(default_device, false, true, devices);
}
}
void CefMediaCaptureDevicesDispatcher::GetRequestedDevice(
const std::string& requested_device_id,
bool audio,
bool video,
content::MediaStreamDevices* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(audio || video);
if (audio) {
const content::MediaStreamDevices& audio_devices = GetAudioCaptureDevices();
const content::MediaStreamDevice* const device =
FindDefaultDeviceWithId(audio_devices, requested_device_id);
if (device)
devices->push_back(*device);
}
if (video) {
const content::MediaStreamDevices& video_devices = GetVideoCaptureDevices();
const content::MediaStreamDevice* const device =
FindDefaultDeviceWithId(video_devices, requested_device_id);
if (device)
devices->push_back(*device);
}
}
void CefMediaCaptureDevicesDispatcher::OnCaptureDevicesOpened(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices,
const base::Closure& close_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
void CefMediaCaptureDevicesDispatcher::OnCaptureDevicesClosed(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
void CefMediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateAudioDevicesOnUIThread,
base::Unretained(this), devices));
}
void CefMediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateVideoDevicesOnUIThread,
base::Unretained(this), devices));
}
void CefMediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateMediaRequestStateOnUIThread,
base::Unretained(this), render_process_id, render_view_id, device,
state));
}
void CefMediaCaptureDevicesDispatcher::OnAudioStreamPlayingChanged(
int render_process_id, int render_view_id, int stream_id, bool playing) {
}
void CefMediaCaptureDevicesDispatcher::UpdateAudioDevicesOnUIThread(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
devices_enumerated_ = true;
audio_devices_ = devices;
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateAudioDevices(audio_devices_));
}
void CefMediaCaptureDevicesDispatcher::UpdateVideoDevicesOnUIThread(
const content::MediaStreamDevices& devices){
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
devices_enumerated_ = true;
video_devices_ = devices;
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateVideoDevices(video_devices_));
}
void CefMediaCaptureDevicesDispatcher::UpdateMediaRequestStateOnUIThread(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) {
FOR_EACH_OBSERVER(Observer, observers_,
OnRequestUpdate(render_process_id,
render_view_id,
device,
state));
}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/media_capture_devices_dispatcher.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/media_devices_monitor.h"
#include "content/public/common/media_stream_request.h"
using content::BrowserThread;
using content::MediaStreamDevices;
namespace {
const content::MediaStreamDevice* FindDefaultDeviceWithId(
const content::MediaStreamDevices& devices,
const std::string& device_id) {
if (devices.empty())
return NULL;
content::MediaStreamDevices::const_iterator iter = devices.begin();
for (; iter != devices.end(); ++iter) {
if (iter->id == device_id) {
return &(*iter);
}
}
return &(*devices.begin());
};
} // namespace
CefMediaCaptureDevicesDispatcher*
CefMediaCaptureDevicesDispatcher::GetInstance() {
return Singleton<CefMediaCaptureDevicesDispatcher>::get();
}
CefMediaCaptureDevicesDispatcher::CefMediaCaptureDevicesDispatcher()
: devices_enumerated_(false) {}
CefMediaCaptureDevicesDispatcher::~CefMediaCaptureDevicesDispatcher() {}
void CefMediaCaptureDevicesDispatcher::RegisterPrefs(
PrefRegistrySimple* registry) {
registry->RegisterStringPref(prefs::kDefaultAudioCaptureDevice,
std::string());
registry->RegisterStringPref(prefs::kDefaultVideoCaptureDevice,
std::string());
}
void CefMediaCaptureDevicesDispatcher::AddObserver(Observer* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!observers_.HasObserver(observer))
observers_.AddObserver(observer);
}
void CefMediaCaptureDevicesDispatcher::RemoveObserver(Observer* observer) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observers_.RemoveObserver(observer);
}
const MediaStreamDevices&
CefMediaCaptureDevicesDispatcher::GetAudioCaptureDevices() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!devices_enumerated_) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&content::EnsureMonitorCaptureDevices));
devices_enumerated_ = true;
}
return audio_devices_;
}
const MediaStreamDevices&
CefMediaCaptureDevicesDispatcher::GetVideoCaptureDevices() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!devices_enumerated_) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&content::EnsureMonitorCaptureDevices));
devices_enumerated_ = true;
}
return video_devices_;
}
void CefMediaCaptureDevicesDispatcher::GetDefaultDevices(
PrefService* prefs,
bool audio,
bool video,
content::MediaStreamDevices* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(audio || video);
std::string default_device;
if (audio) {
default_device = prefs->GetString(prefs::kDefaultAudioCaptureDevice);
GetRequestedDevice(default_device, true, false, devices);
}
if (video) {
default_device = prefs->GetString(prefs::kDefaultVideoCaptureDevice);
GetRequestedDevice(default_device, false, true, devices);
}
}
void CefMediaCaptureDevicesDispatcher::GetRequestedDevice(
const std::string& requested_device_id,
bool audio,
bool video,
content::MediaStreamDevices* devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(audio || video);
if (audio) {
const content::MediaStreamDevices& audio_devices = GetAudioCaptureDevices();
const content::MediaStreamDevice* const device =
FindDefaultDeviceWithId(audio_devices, requested_device_id);
if (device)
devices->push_back(*device);
}
if (video) {
const content::MediaStreamDevices& video_devices = GetVideoCaptureDevices();
const content::MediaStreamDevice* const device =
FindDefaultDeviceWithId(video_devices, requested_device_id);
if (device)
devices->push_back(*device);
}
}
void CefMediaCaptureDevicesDispatcher::OnCaptureDevicesOpened(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices,
const base::Closure& close_callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
void CefMediaCaptureDevicesDispatcher::OnCaptureDevicesClosed(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
void CefMediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateAudioDevicesOnUIThread,
base::Unretained(this), devices));
}
void CefMediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateVideoDevicesOnUIThread,
base::Unretained(this), devices));
}
void CefMediaCaptureDevicesDispatcher::OnMediaRequestStateChanged(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&CefMediaCaptureDevicesDispatcher::UpdateMediaRequestStateOnUIThread,
base::Unretained(this), render_process_id, render_view_id, device,
state));
}
void CefMediaCaptureDevicesDispatcher::OnAudioStreamPlayingChanged(
int render_process_id, int render_view_id, int stream_id, bool playing) {
}
void CefMediaCaptureDevicesDispatcher::UpdateAudioDevicesOnUIThread(
const content::MediaStreamDevices& devices) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
devices_enumerated_ = true;
audio_devices_ = devices;
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateAudioDevices(audio_devices_));
}
void CefMediaCaptureDevicesDispatcher::UpdateVideoDevicesOnUIThread(
const content::MediaStreamDevices& devices){
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
devices_enumerated_ = true;
video_devices_ = devices;
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateVideoDevices(video_devices_));
}
void CefMediaCaptureDevicesDispatcher::UpdateMediaRequestStateOnUIThread(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) {
FOR_EACH_OBSERVER(Observer, observers_,
OnRequestUpdate(render_process_id,
render_view_id,
device,
state));
}

View File

@ -1,129 +1,129 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_
#define CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/observer_list.h"
#include "content/public/browser/media_observer.h"
#include "content/public/common/media_stream_request.h"
class PrefRegistrySimple;
class PrefService;
// This singleton is used to receive updates about media events from the content
// layer. Based on chrome/browser/media/media_capture_devices_dispatcher.[h|cc].
class CefMediaCaptureDevicesDispatcher : public content::MediaObserver {
public:
class Observer {
public:
// Handle an information update consisting of a up-to-date audio capture
// device lists. This happens when a microphone is plugged in or unplugged.
virtual void OnUpdateAudioDevices(
const content::MediaStreamDevices& devices) {}
// Handle an information update consisting of a up-to-date video capture
// device lists. This happens when a camera is plugged in or unplugged.
virtual void OnUpdateVideoDevices(
const content::MediaStreamDevices& devices) {}
// Handle an information update related to a media stream request.
virtual void OnRequestUpdate(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
const content::MediaRequestState state) {}
virtual ~Observer() {}
};
static CefMediaCaptureDevicesDispatcher* GetInstance();
// Registers the preferences related to Media Stream default devices.
static void RegisterPrefs(PrefRegistrySimple* registry);
// Methods for observers. Called on UI thread.
// Observers should add themselves on construction and remove themselves
// on destruction.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
const content::MediaStreamDevices& GetAudioCaptureDevices();
const content::MediaStreamDevices& GetVideoCaptureDevices();
// Helper to get the default devices which can be used by the media request,
// if the return list is empty, it means there is no available device on the
// OS.
// Called on the UI thread.
void GetDefaultDevices(PrefService* prefs,
bool audio,
bool video,
content::MediaStreamDevices* devices);
// Helper for picking the device that was requested for an OpenDevice request.
// If the device requested is not available it will revert to using the first
// available one instead or will return an empty list if no devices of the
// requested kind are present.
void GetRequestedDevice(const std::string& requested_device_id,
bool audio,
bool video,
content::MediaStreamDevices* devices);
// Overridden from content::MediaObserver:
virtual void OnCaptureDevicesOpened(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices,
const base::Closure& close_callback) OVERRIDE;
virtual void OnCaptureDevicesClosed(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnAudioCaptureDevicesChanged(
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnVideoCaptureDevicesChanged(
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnMediaRequestStateChanged(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) OVERRIDE;
virtual void OnAudioStreamPlayingChanged(
int render_process_id,
int render_view_id,
int stream_id,
bool playing) OVERRIDE;
private:
friend struct DefaultSingletonTraits<CefMediaCaptureDevicesDispatcher>;
CefMediaCaptureDevicesDispatcher();
virtual ~CefMediaCaptureDevicesDispatcher();
// Called by the MediaObserver() functions, executed on UI thread.
void UpdateAudioDevicesOnUIThread(const content::MediaStreamDevices& devices);
void UpdateVideoDevicesOnUIThread(const content::MediaStreamDevices& devices);
void UpdateMediaRequestStateOnUIThread(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state);
// A list of cached audio capture devices.
content::MediaStreamDevices audio_devices_;
// A list of cached video capture devices.
content::MediaStreamDevices video_devices_;
// A list of observers for the device update notifications.
ObserverList<Observer> observers_;
// Flag to indicate if device enumeration has been done/doing.
// Only accessed on UI thread.
bool devices_enumerated_;
};
#endif // CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_
#define CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/observer_list.h"
#include "content/public/browser/media_observer.h"
#include "content/public/common/media_stream_request.h"
class PrefRegistrySimple;
class PrefService;
// This singleton is used to receive updates about media events from the content
// layer. Based on chrome/browser/media/media_capture_devices_dispatcher.[h|cc].
class CefMediaCaptureDevicesDispatcher : public content::MediaObserver {
public:
class Observer {
public:
// Handle an information update consisting of a up-to-date audio capture
// device lists. This happens when a microphone is plugged in or unplugged.
virtual void OnUpdateAudioDevices(
const content::MediaStreamDevices& devices) {}
// Handle an information update consisting of a up-to-date video capture
// device lists. This happens when a camera is plugged in or unplugged.
virtual void OnUpdateVideoDevices(
const content::MediaStreamDevices& devices) {}
// Handle an information update related to a media stream request.
virtual void OnRequestUpdate(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
const content::MediaRequestState state) {}
virtual ~Observer() {}
};
static CefMediaCaptureDevicesDispatcher* GetInstance();
// Registers the preferences related to Media Stream default devices.
static void RegisterPrefs(PrefRegistrySimple* registry);
// Methods for observers. Called on UI thread.
// Observers should add themselves on construction and remove themselves
// on destruction.
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
const content::MediaStreamDevices& GetAudioCaptureDevices();
const content::MediaStreamDevices& GetVideoCaptureDevices();
// Helper to get the default devices which can be used by the media request,
// if the return list is empty, it means there is no available device on the
// OS.
// Called on the UI thread.
void GetDefaultDevices(PrefService* prefs,
bool audio,
bool video,
content::MediaStreamDevices* devices);
// Helper for picking the device that was requested for an OpenDevice request.
// If the device requested is not available it will revert to using the first
// available one instead or will return an empty list if no devices of the
// requested kind are present.
void GetRequestedDevice(const std::string& requested_device_id,
bool audio,
bool video,
content::MediaStreamDevices* devices);
// Overridden from content::MediaObserver:
virtual void OnCaptureDevicesOpened(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices,
const base::Closure& close_callback) OVERRIDE;
virtual void OnCaptureDevicesClosed(
int render_process_id,
int render_view_id,
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnAudioCaptureDevicesChanged(
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnVideoCaptureDevicesChanged(
const content::MediaStreamDevices& devices) OVERRIDE;
virtual void OnMediaRequestStateChanged(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state) OVERRIDE;
virtual void OnAudioStreamPlayingChanged(
int render_process_id,
int render_view_id,
int stream_id,
bool playing) OVERRIDE;
private:
friend struct DefaultSingletonTraits<CefMediaCaptureDevicesDispatcher>;
CefMediaCaptureDevicesDispatcher();
virtual ~CefMediaCaptureDevicesDispatcher();
// Called by the MediaObserver() functions, executed on UI thread.
void UpdateAudioDevicesOnUIThread(const content::MediaStreamDevices& devices);
void UpdateVideoDevicesOnUIThread(const content::MediaStreamDevices& devices);
void UpdateMediaRequestStateOnUIThread(
int render_process_id,
int render_view_id,
const content::MediaStreamDevice& device,
content::MediaRequestState state);
// A list of cached audio capture devices.
content::MediaStreamDevices audio_devices_;
// A list of cached video capture devices.
content::MediaStreamDevices video_devices_;
// A list of observers for the device update notifications.
ObserverList<Observer> observers_;
// Flag to indicate if device enumeration has been done/doing.
// Only accessed on UI thread.
bool devices_enumerated_;
};
#endif // CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_

View File

@ -1,14 +1,14 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "components/user_prefs/pref_registry_syncable.h"
// Required by PrefProxyConfigTrackerImpl::RegisterUserPrefs.
void PrefRegistrySyncable::RegisterDictionaryPref(
const char* path,
base::DictionaryValue* default_value,
PrefSyncStatus sync_status) {
NOTREACHED();
}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "components/user_prefs/pref_registry_syncable.h"
// Required by PrefProxyConfigTrackerImpl::RegisterUserPrefs.
void PrefRegistrySyncable::RegisterDictionaryPref(
const char* path,
base::DictionaryValue* default_value,
PrefSyncStatus sync_status) {
NOTREACHED();
}

View File

@ -1,8 +1,8 @@
Index: browser/web_contents/web_drag_dest_gtk.cc
===================================================================
--- browser/web_contents/web_drag_dest_gtk.cc (revision 202711)
+++ browser/web_contents/web_drag_dest_gtk.cc (working copy)
@@ -13,6 +13,7 @@
Index: browser/web_contents/web_drag_dest_gtk.cc
===================================================================
--- browser/web_contents/web_drag_dest_gtk.cc (revision 202711)
+++ browser/web_contents/web_drag_dest_gtk.cc (working copy)
@@ -13,6 +13,7 @@
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/drag_utils_gtk.h"
#include "content/browser/web_contents/web_contents_impl.h"
@ -10,7 +10,7 @@ Index: browser/web_contents/web_drag_dest_gtk.cc
#include "content/public/browser/web_drag_dest_delegate.h"
#include "content/public/common/url_constants.h"
#include "net/base/net_util.h"
@@ -53,6 +54,7 @@
@@ -53,6 +54,7 @@
context_(NULL),
data_requests_(0),
delegate_(NULL),
@ -18,7 +18,7 @@ Index: browser/web_contents/web_drag_dest_gtk.cc
method_factory_(this) {
gtk_drag_dest_set(widget, static_cast<GtkDestDefaults>(0),
NULL, 0,
@@ -143,6 +145,9 @@
@@ -143,6 +145,9 @@
time);
}
} else if (data_requests_ == 0) {
@ -28,7 +28,7 @@ Index: browser/web_contents/web_drag_dest_gtk.cc
GetRenderViewHost()->DragTargetDragOver(
ui::ClientPoint(widget_),
ui::ScreenPoint(widget_),
@@ -236,6 +241,20 @@
@@ -236,6 +241,20 @@
}
}
@ -49,7 +49,7 @@ Index: browser/web_contents/web_drag_dest_gtk.cc
// For CHROME_BOOKMARK_ITEM, we have to handle the case where the drag source
// doesn't have any data available for us. In this case we try to synthesize a
// URL bookmark.
@@ -274,6 +293,9 @@
@@ -274,6 +293,9 @@
// as an enter.
context_ = NULL;
@ -59,11 +59,11 @@ Index: browser/web_contents/web_drag_dest_gtk.cc
// Sometimes we get a drag-leave event before getting a drag-data-received
// event. In that case, we don't want to bother the renderer with a
// DragLeave event.
Index: browser/web_contents/web_drag_dest_gtk.h
===================================================================
--- browser/web_contents/web_drag_dest_gtk.h (revision 202711)
+++ browser/web_contents/web_drag_dest_gtk.h (working copy)
@@ -101,6 +101,9 @@
Index: browser/web_contents/web_drag_dest_gtk.h
===================================================================
--- browser/web_contents/web_drag_dest_gtk.h (revision 202711)
+++ browser/web_contents/web_drag_dest_gtk.h (working copy)
@@ -101,6 +101,9 @@
// A delegate that can receive drag information about drag events.
WebDragDestDelegate* delegate_;
@ -73,11 +73,11 @@ Index: browser/web_contents/web_drag_dest_gtk.h
base::WeakPtrFactory<WebDragDestGtk> method_factory_;
DISALLOW_COPY_AND_ASSIGN(WebDragDestGtk);
Index: browser/web_contents/web_drag_dest_mac.h
===================================================================
--- browser/web_contents/web_drag_dest_mac.h (revision 202711)
+++ browser/web_contents/web_drag_dest_mac.h (working copy)
@@ -40,6 +40,9 @@
Index: browser/web_contents/web_drag_dest_mac.h
===================================================================
--- browser/web_contents/web_drag_dest_mac.h (revision 202711)
+++ browser/web_contents/web_drag_dest_mac.h (working copy)
@@ -40,6 +40,9 @@
// The data for the current drag, or NULL if none is in progress.
scoped_ptr<WebDropData> dropData_;
@ -87,11 +87,11 @@ Index: browser/web_contents/web_drag_dest_mac.h
}
// |contents| is the WebContentsImpl representing this tab, used to communicate
Index: browser/web_contents/web_drag_dest_mac.mm
===================================================================
--- browser/web_contents/web_drag_dest_mac.mm (revision 202711)
+++ browser/web_contents/web_drag_dest_mac.mm (working copy)
@@ -9,6 +9,7 @@
Index: browser/web_contents/web_drag_dest_mac.mm
===================================================================
--- browser/web_contents/web_drag_dest_mac.mm (revision 202711)
+++ browser/web_contents/web_drag_dest_mac.mm (working copy)
@@ -9,6 +9,7 @@
#include "base/sys_string_conversions.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_contents_impl.h"
@ -99,7 +99,7 @@ Index: browser/web_contents/web_drag_dest_mac.mm
#include "content/public/browser/web_drag_dest_delegate.h"
#import "third_party/mozilla/NSPasteboard+Utils.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
@@ -44,6 +45,7 @@
@@ -44,6 +45,7 @@
- (id)initWithWebContentsImpl:(WebContentsImpl*)contents {
if ((self = [super init])) {
webContents_ = contents;
@ -107,7 +107,7 @@ Index: browser/web_contents/web_drag_dest_mac.mm
}
return self;
}
@@ -103,6 +105,22 @@
@@ -103,6 +105,22 @@
// we need to send a new enter message in draggingUpdated:.
currentRVH_ = webContents_->GetRenderViewHost();
@ -130,7 +130,7 @@ Index: browser/web_contents/web_drag_dest_mac.mm
if ([self onlyAllowsNavigation]) {
if ([[info draggingPasteboard] containsURLData])
return NSDragOperationCopy;
@@ -114,17 +132,13 @@
@@ -114,17 +132,13 @@
delegate_->OnDragEnter();
}
@ -149,7 +149,7 @@ Index: browser/web_contents/web_drag_dest_mac.mm
webContents_->GetRenderViewHost()->DragTargetDragEnter(
*dropData_,
gfx::Point(viewPoint.x, viewPoint.y),
@@ -143,6 +157,9 @@
@@ -143,6 +157,9 @@
if (currentRVH_ != webContents_->GetRenderViewHost())
return;
@ -159,7 +159,7 @@ Index: browser/web_contents/web_drag_dest_mac.mm
if ([self onlyAllowsNavigation])
return;
@@ -159,6 +176,9 @@
@@ -159,6 +176,9 @@
if (currentRVH_ != webContents_->GetRenderViewHost())
[self draggingEntered:info view:view];
@ -169,11 +169,11 @@ Index: browser/web_contents/web_drag_dest_mac.mm
if ([self onlyAllowsNavigation]) {
if ([[info draggingPasteboard] containsURLData])
return NSDragOperationCopy;
Index: browser/web_contents/web_drag_dest_win.cc
===================================================================
--- browser/web_contents/web_drag_dest_win.cc (revision 202711)
+++ browser/web_contents/web_drag_dest_win.cc (working copy)
@@ -11,6 +11,7 @@
Index: browser/web_contents/web_drag_dest_win.cc
===================================================================
--- browser/web_contents/web_drag_dest_win.cc (revision 202711)
+++ browser/web_contents/web_drag_dest_win.cc (working copy)
@@ -11,6 +11,7 @@
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/web_contents/web_drag_utils_win.h"
#include "content/public/browser/web_contents.h"
@ -181,7 +181,7 @@ Index: browser/web_contents/web_drag_dest_win.cc
#include "content/public/browser/web_drag_dest_delegate.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
@@ -108,7 +109,8 @@
@@ -108,7 +109,8 @@
current_rvh_(NULL),
drag_cursor_(WebDragOperationNone),
interstitial_drop_target_(new InterstitialDropTarget(web_contents)),
@ -191,7 +191,7 @@ Index: browser/web_contents/web_drag_dest_win.cc
}
WebDragDest::~WebDragDest() {
@@ -120,6 +122,24 @@
@@ -120,6 +122,24 @@
DWORD effects) {
current_rvh_ = web_contents_->GetRenderViewHost();
@ -216,7 +216,7 @@ Index: browser/web_contents/web_drag_dest_win.cc
if (delegate_)
delegate_->DragInitialize(web_contents_);
@@ -129,15 +149,7 @@
@@ -129,15 +149,7 @@
if (web_contents_->ShowingInterstitialPage())
return interstitial_drop_target_->OnDragEnter(data_object, effects);
@ -233,7 +233,7 @@ Index: browser/web_contents/web_drag_dest_win.cc
drag_cursor_ = WebDragOperationNone;
POINT client_pt = cursor_position;
@@ -164,6 +176,9 @@
@@ -164,6 +176,9 @@
if (current_rvh_ != web_contents_->GetRenderViewHost())
OnDragEnter(data_object, key_state, cursor_position, effects);
@ -243,7 +243,7 @@ Index: browser/web_contents/web_drag_dest_win.cc
if (web_contents_->ShowingInterstitialPage())
return interstitial_drop_target_->OnDragOver(data_object, effects);
@@ -186,6 +201,9 @@
@@ -186,6 +201,9 @@
if (current_rvh_ != web_contents_->GetRenderViewHost())
return;
@ -253,11 +253,11 @@ Index: browser/web_contents/web_drag_dest_win.cc
if (web_contents_->ShowingInterstitialPage()) {
interstitial_drop_target_->OnDragLeave(data_object);
} else {
Index: browser/web_contents/web_drag_dest_win.h
===================================================================
--- browser/web_contents/web_drag_dest_win.h (revision 202711)
+++ browser/web_contents/web_drag_dest_win.h (working copy)
@@ -78,6 +78,9 @@
Index: browser/web_contents/web_drag_dest_win.h
===================================================================
--- browser/web_contents/web_drag_dest_win.h (revision 202711)
+++ browser/web_contents/web_drag_dest_win.h (working copy)
@@ -78,6 +78,9 @@
// The data for the current drag, or NULL if |context_| is NULL.
scoped_ptr<WebDropData> drop_data_;
@ -267,11 +267,11 @@ Index: browser/web_contents/web_drag_dest_win.h
DISALLOW_COPY_AND_ASSIGN(WebDragDest);
};
Index: public/browser/web_contents_delegate.cc
===================================================================
--- public/browser/web_contents_delegate.cc (revision 202711)
+++ public/browser/web_contents_delegate.cc (working copy)
@@ -110,6 +110,13 @@
Index: public/browser/web_contents_delegate.cc
===================================================================
--- public/browser/web_contents_delegate.cc (revision 202711)
+++ public/browser/web_contents_delegate.cc (working copy)
@@ -110,6 +110,13 @@
return false;
}
@ -285,11 +285,11 @@ Index: public/browser/web_contents_delegate.cc
bool WebContentsDelegate::OnGoToEntryOffset(int offset) {
return true;
}
Index: public/browser/web_contents_delegate.h
===================================================================
--- public/browser/web_contents_delegate.h (revision 202711)
+++ public/browser/web_contents_delegate.h (working copy)
@@ -17,11 +17,13 @@
Index: public/browser/web_contents_delegate.h
===================================================================
--- public/browser/web_contents_delegate.h (revision 202711)
+++ public/browser/web_contents_delegate.h (working copy)
@@ -17,11 +17,13 @@
#include "content/public/common/page_transition_types.h"
#include "content/public/common/window_container_type.h"
#include "third_party/skia/include/core/SkColor.h"
@ -303,7 +303,7 @@ Index: public/browser/web_contents_delegate.h
namespace base {
class FilePath;
@@ -264,6 +266,13 @@
@@ -264,6 +266,13 @@
virtual void HandleGestureBegin() {}
virtual void HandleGestureEnd() {}

View File

@ -1,22 +1,22 @@
Index: gyp/generator/ninja.py
===================================================================
--- gyp/generator/ninja.py (revision 1602)
+++ gyp/generator/ninja.py (working copy)
@@ -662,7 +662,16 @@
for path in copy['files']:
# Normalize the path so trailing slashes don't confuse us.
path = os.path.normpath(path)
- basename = os.path.split(path)[1]
+ (parent_path, basename) = os.path.split(path)
+
+ # Xcode uses .lproj directories for localized resources. Add a special
+ # case to maintain the localization directory component if present.
+ if parent_path != '':
+ parent_basename = os.path.basename(parent_path)
+ (parent_root, parent_ext) = os.path.splitext(parent_basename)
+ if parent_ext == '.lproj':
+ basename = os.path.join(parent_basename, basename)
+
src = self.GypPathToNinja(path, env)
dst = self.GypPathToNinja(os.path.join(copy['destination'], basename),
env)
Index: gyp/generator/ninja.py
===================================================================
--- gyp/generator/ninja.py (revision 1602)
+++ gyp/generator/ninja.py (working copy)
@@ -662,7 +662,16 @@
for path in copy['files']:
# Normalize the path so trailing slashes don't confuse us.
path = os.path.normpath(path)
- basename = os.path.split(path)[1]
+ (parent_path, basename) = os.path.split(path)
+
+ # Xcode uses .lproj directories for localized resources. Add a special
+ # case to maintain the localization directory component if present.
+ if parent_path != '':
+ parent_basename = os.path.basename(parent_path)
+ (parent_root, parent_ext) = os.path.splitext(parent_basename)
+ if parent_ext == '.lproj':
+ basename = os.path.join(parent_basename, basename)
+
src = self.GypPathToNinja(path, env)
dst = self.GypPathToNinja(os.path.join(copy['destination'], basename),
env)

View File

@ -1,8 +1,8 @@
Index: render_widget_host_view_mac.mm
===================================================================
--- render_widget_host_view_mac.mm (revision 202711)
+++ render_widget_host_view_mac.mm (working copy)
@@ -4,6 +4,7 @@
Index: render_widget_host_view_mac.mm
===================================================================
--- render_widget_host_view_mac.mm (revision 202711)
+++ render_widget_host_view_mac.mm (working copy)
@@ -4,6 +4,7 @@
#include "content/browser/renderer_host/render_widget_host_view_mac.h"
@ -10,7 +10,7 @@ Index: render_widget_host_view_mac.mm
#include <QuartzCore/QuartzCore.h>
#include "base/bind.h"
@@ -125,6 +126,29 @@
@@ -125,6 +126,29 @@
return modifiers;
}
@ -40,7 +40,7 @@ Index: render_widget_host_view_mac.mm
static float ScaleFactor(NSView* view) {
return ui::GetScaleFactorScale(ui::GetScaleFactorForNativeView(view));
}
@@ -1424,7 +1448,7 @@
@@ -1424,7 +1448,7 @@
// Forget IOSurface since we are drawing a software frame now.
if (compositing_iosurface_.get() &&
compositing_iosurface_->HasIOSurface()) {
@ -49,7 +49,7 @@ Index: render_widget_host_view_mac.mm
}
}
}
@@ -2097,13 +2121,21 @@
@@ -2097,13 +2121,21 @@
NSNotificationCenter* notificationCenter =
[NSNotificationCenter defaultCenter];
@ -75,7 +75,7 @@ Index: render_widget_host_view_mac.mm
name:NSWindowDidMoveNotification
object:oldWindow];
[notificationCenter
@@ -2112,13 +2144,15 @@
@@ -2112,13 +2144,15 @@
object:oldWindow];
}
if (newWindow) {

View File

@ -1,8 +1,8 @@
Index: renderer_main.cc
===================================================================
--- renderer_main.cc (revision 197225)
+++ renderer_main.cc (working copy)
@@ -200,7 +200,7 @@
Index: renderer_main.cc
===================================================================
--- renderer_main.cc (revision 197225)
+++ renderer_main.cc (working copy)
@@ -200,7 +200,7 @@
if (!no_sandbox) {
run_loop = platform.EnableSandbox();
} else {

View File

@ -1,8 +1,8 @@
Index: sandbox_win.cc
===================================================================
--- sandbox_win.cc (revision 202711)
+++ sandbox_win.cc (working copy)
@@ -589,8 +589,23 @@
Index: sandbox_win.cc
===================================================================
--- sandbox_win.cc (revision 202711)
+++ sandbox_win.cc (working copy)
@@ -589,8 +589,23 @@
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
if (!in_sandbox) {

View File

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

View File

@ -1,8 +1,8 @@
Index: features.gypi
===================================================================
--- features.gypi (revision 145278)
+++ features.gypi (working copy)
@@ -193,7 +193,7 @@
Index: features.gypi
===================================================================
--- features.gypi (revision 145278)
+++ features.gypi (working copy)
@@ -193,7 +193,7 @@
'ENABLE_CALENDAR_PICKER=1',
'ENABLE_DATALIST_ELEMENT=1',
'ENABLE_INPUT_SPEECH=1',

View File

@ -1,76 +1,76 @@
Index: src/WebViewImpl.cpp
===================================================================
--- src/WebViewImpl.cpp (revision 147958)
+++ src/WebViewImpl.cpp (working copy)
@@ -407,6 +407,7 @@
, m_fakeDoubleTapPageScaleFactor(0)
, m_fakeDoubleTapUseAnchor(false)
, m_contextMenuAllowed(false)
+ , m_shouldUseExternalPopupMenus(shouldUseExternalPopupMenus)
, m_doingDragAndDrop(false)
, m_ignoreInputEvents(false)
, m_suppressNextKeypressEvent(false)
@@ -3823,9 +3824,14 @@
{
}
+void WebViewImpl::setUseExternalPopupMenusThisInstance(bool useExternalPopupMenus)
+{
+ m_shouldUseExternalPopupMenus = useExternalPopupMenus;
+}
+
bool WebViewImpl::useExternalPopupMenus()
{
- return shouldUseExternalPopupMenus;
+ return m_shouldUseExternalPopupMenus;
}
void WebViewImpl::setEmulatedTextZoomFactor(float textZoomFactor)
Index: src/WebViewImpl.h
===================================================================
--- src/WebViewImpl.h (revision 147958)
+++ src/WebViewImpl.h (working copy)
@@ -422,7 +422,8 @@
// Returns true if popup menus should be rendered by the browser, false if
// they should be rendered by WebKit (which is the default).
- static bool useExternalPopupMenus();
+ void setUseExternalPopupMenusThisInstance(bool);
+ bool useExternalPopupMenus();
bool contextMenuAllowed() const
{
@@ -768,6 +769,8 @@
bool m_contextMenuAllowed;
+ bool m_shouldUseExternalPopupMenus;
+
bool m_doingDragAndDrop;
bool m_ignoreInputEvents;
Index: src/ChromeClientImpl.cpp
===================================================================
--- src/ChromeClientImpl.cpp (revision 147958)
+++ src/ChromeClientImpl.cpp (working copy)
@@ -1008,7 +1008,7 @@
PassRefPtr<PopupMenu> ChromeClientImpl::createPopupMenu(PopupMenuClient* client) const
{
- if (WebViewImpl::useExternalPopupMenus())
+ if (m_webView->useExternalPopupMenus())
return adoptRef(new ExternalPopupMenu(client, m_webView->client()));
return adoptRef(new PopupMenuChromium(client));
Index: public/WebView.h
===================================================================
--- public/WebView.h (revision 147958)
+++ public/WebView.h (working copy)
@@ -419,6 +419,7 @@
// Sets whether select popup menus should be rendered by the browser.
WEBKIT_EXPORT static void setUseExternalPopupMenus(bool);
+ virtual void setUseExternalPopupMenusThisInstance(bool) = 0;
// Visited link state --------------------------------------------------
Index: src/WebViewImpl.cpp
===================================================================
--- src/WebViewImpl.cpp (revision 147958)
+++ src/WebViewImpl.cpp (working copy)
@@ -407,6 +407,7 @@
, m_fakeDoubleTapPageScaleFactor(0)
, m_fakeDoubleTapUseAnchor(false)
, m_contextMenuAllowed(false)
+ , m_shouldUseExternalPopupMenus(shouldUseExternalPopupMenus)
, m_doingDragAndDrop(false)
, m_ignoreInputEvents(false)
, m_suppressNextKeypressEvent(false)
@@ -3823,9 +3824,14 @@
{
}
+void WebViewImpl::setUseExternalPopupMenusThisInstance(bool useExternalPopupMenus)
+{
+ m_shouldUseExternalPopupMenus = useExternalPopupMenus;
+}
+
bool WebViewImpl::useExternalPopupMenus()
{
- return shouldUseExternalPopupMenus;
+ return m_shouldUseExternalPopupMenus;
}
void WebViewImpl::setEmulatedTextZoomFactor(float textZoomFactor)
Index: src/WebViewImpl.h
===================================================================
--- src/WebViewImpl.h (revision 147958)
+++ src/WebViewImpl.h (working copy)
@@ -422,7 +422,8 @@
// Returns true if popup menus should be rendered by the browser, false if
// they should be rendered by WebKit (which is the default).
- static bool useExternalPopupMenus();
+ void setUseExternalPopupMenusThisInstance(bool);
+ bool useExternalPopupMenus();
bool contextMenuAllowed() const
{
@@ -768,6 +769,8 @@
bool m_contextMenuAllowed;
+ bool m_shouldUseExternalPopupMenus;
+
bool m_doingDragAndDrop;
bool m_ignoreInputEvents;
Index: src/ChromeClientImpl.cpp
===================================================================
--- src/ChromeClientImpl.cpp (revision 147958)
+++ src/ChromeClientImpl.cpp (working copy)
@@ -1008,7 +1008,7 @@
PassRefPtr<PopupMenu> ChromeClientImpl::createPopupMenu(PopupMenuClient* client) const
{
- if (WebViewImpl::useExternalPopupMenus())
+ if (m_webView->useExternalPopupMenus())
return adoptRef(new ExternalPopupMenu(client, m_webView->client()));
return adoptRef(new PopupMenuChromium(client));
Index: public/WebView.h
===================================================================
--- public/WebView.h (revision 147958)
+++ public/WebView.h (working copy)
@@ -419,6 +419,7 @@
// Sets whether select popup menus should be rendered by the browser.
WEBKIT_EXPORT static void setUseExternalPopupMenus(bool);
+ virtual void setUseExternalPopupMenusThisInstance(bool) = 0;
// Visited link state --------------------------------------------------

View File

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

View File

@ -1,90 +1,90 @@
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#pragma once
#include "include/cef_render_handler.h"
#include "cefclient/client_handler.h"
#include "cefclient/osrenderer.h"
class OSRBrowserProvider {
public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected:
virtual ~OSRBrowserProvider() {}
};
class OSRWindow : public ClientHandler::RenderHandler {
public:
// Create a new OSRWindow instance. |browser_provider| must outlive this
// object.
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView);
static CefRefPtr<OSRWindow> From(
CefRefPtr<ClientHandler::RenderHandler> renderHandler);
CefWindowHandle GetWindowHandle() const {
return glarea_;
}
CefRefPtr<CefBrowserHost> GetBrowserHost() const {
return browser_provider_->GetBrowser()->GetHost();
}
// ClientHandler::RenderHandler methods
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer,
int width,
int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE;
void Invalidate();
bool IsOverPopupWidget(int x, int y) const;
int GetPopupXOffset() const;
int GetPopupYOffset() const;
void ApplyPopupOffset(int& x, int& y) const;
private:
OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView);
virtual ~OSRWindow();
void Render();
void EnableGL();
void DisableGL();
ClientOSRenderer renderer_;
OSRBrowserProvider* browser_provider_;
CefWindowHandle glarea_;
bool gl_enabled_;
bool painting_popup_;
bool render_task_pending_;
IMPLEMENT_REFCOUNTING(OSRWindow);
};
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_GTK_H_
#pragma once
#include "include/cef_render_handler.h"
#include "cefclient/client_handler.h"
#include "cefclient/osrenderer.h"
class OSRBrowserProvider {
public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected:
virtual ~OSRBrowserProvider() {}
};
class OSRWindow : public ClientHandler::RenderHandler {
public:
// Create a new OSRWindow instance. |browser_provider| must outlive this
// object.
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView);
static CefRefPtr<OSRWindow> From(
CefRefPtr<ClientHandler::RenderHandler> renderHandler);
CefWindowHandle GetWindowHandle() const {
return glarea_;
}
CefRefPtr<CefBrowserHost> GetBrowserHost() const {
return browser_provider_->GetBrowser()->GetHost();
}
// ClientHandler::RenderHandler methods
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer,
int width,
int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE;
void Invalidate();
bool IsOverPopupWidget(int x, int y) const;
int GetPopupXOffset() const;
int GetPopupYOffset() const;
void ApplyPopupOffset(int& x, int& y) const;
private:
OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView);
virtual ~OSRWindow();
void Render();
void EnableGL();
void DisableGL();
ClientOSRenderer renderer_;
OSRBrowserProvider* browser_provider_;
CefWindowHandle glarea_;
bool gl_enabled_;
bool painting_popup_;
bool render_task_pending_;
IMPLEMENT_REFCOUNTING(OSRWindow);
};
#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
// reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#include "include/cef_client.h"
#include "cefclient/client_handler.h"
class ClientOSRenderer;
class OSRBrowserProvider {
public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected:
virtual ~OSRBrowserProvider() {}
};
// The client OpenGL view.
@interface ClientOpenGLView : NSOpenGLView {
@public
NSTrackingArea* tracking_area_;
OSRBrowserProvider* browser_provider_;
ClientOSRenderer* renderer_;
NSPoint last_mouse_pos_;
NSPoint cur_mouse_pos_;
bool rotating_;
bool was_last_mouse_down_on_view_;
// Event monitor for scroll wheel end event.
id endWheelMonitor_;
}
- (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency;
- (NSPoint)getClickPointForEvent:(NSEvent*)event;
- (void)getKeyEvent:(CefKeyEvent&)keyEvent forEvent:(NSEvent*)event;
- (void)getMouseEvent:(CefMouseEvent&)mouseEvent forEvent:(NSEvent*)event;
- (int)getModifiersForEvent:(NSEvent*)event;
- (BOOL)isKeyUpEvent:(NSEvent*)event;
- (BOOL)isKeyPadEvent:(NSEvent*)event;
- (CefRefPtr<CefBrowser>)getBrowser;
@end
// Handler for off-screen rendering windows.
class ClientOSRHandler : public ClientHandler::RenderHandler {
public:
explicit ClientOSRHandler(ClientOpenGLView* view,
OSRBrowserProvider* browser_provider);
virtual ~ClientOSRHandler();
void Disconnect();
// ClientHandler::RenderHandler
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) OVERRIDE;
virtual bool GetScreenInfo(CefRefPtr<CefBrowser> browser,
CefScreenInfo& screen_info) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer,
int width, int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE;
CefWindowHandle view() { return view_; }
private:
void SetLoading(bool isLoading);
ClientOpenGLView* view_;
bool painting_popup_;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientOSRHandler);
};
class OSRWindow {
public:
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView,
const CefRect& frame);
CefRefPtr<ClientHandler::RenderHandler> GetRenderHandler() {
return render_client.get();
}
CefWindowHandle GetWindowHandle() { return view_; }
private:
OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView,
const CefRect& frame);
~OSRWindow();
CefRefPtr<ClientOSRHandler> render_client;
CefWindowHandle view_;
IMPLEMENT_REFCOUNTING(OSRWindow);
};
#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#define CEF_TESTS_CEFCLIENT_CEFCLIENT_OSR_WIDGET_MAC_H_
#include "include/cef_client.h"
#include "cefclient/client_handler.h"
class ClientOSRenderer;
class OSRBrowserProvider {
public:
virtual CefRefPtr<CefBrowser> GetBrowser() =0;
protected:
virtual ~OSRBrowserProvider() {}
};
// The client OpenGL view.
@interface ClientOpenGLView : NSOpenGLView {
@public
NSTrackingArea* tracking_area_;
OSRBrowserProvider* browser_provider_;
ClientOSRenderer* renderer_;
NSPoint last_mouse_pos_;
NSPoint cur_mouse_pos_;
bool rotating_;
bool was_last_mouse_down_on_view_;
// Event monitor for scroll wheel end event.
id endWheelMonitor_;
}
- (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency;
- (NSPoint)getClickPointForEvent:(NSEvent*)event;
- (void)getKeyEvent:(CefKeyEvent&)keyEvent forEvent:(NSEvent*)event;
- (void)getMouseEvent:(CefMouseEvent&)mouseEvent forEvent:(NSEvent*)event;
- (int)getModifiersForEvent:(NSEvent*)event;
- (BOOL)isKeyUpEvent:(NSEvent*)event;
- (BOOL)isKeyPadEvent:(NSEvent*)event;
- (CefRefPtr<CefBrowser>)getBrowser;
@end
// Handler for off-screen rendering windows.
class ClientOSRHandler : public ClientHandler::RenderHandler {
public:
explicit ClientOSRHandler(ClientOpenGLView* view,
OSRBrowserProvider* browser_provider);
virtual ~ClientOSRHandler();
void Disconnect();
// ClientHandler::RenderHandler
virtual void OnBeforeClose(CefRefPtr<CefBrowser> browser) OVERRIDE;
// CefRenderHandler methods
virtual bool GetViewRect(CefRefPtr<CefBrowser> browser,
CefRect& rect) OVERRIDE;
virtual bool GetScreenPoint(CefRefPtr<CefBrowser> browser,
int viewX,
int viewY,
int& screenX,
int& screenY) OVERRIDE;
virtual bool GetScreenInfo(CefRefPtr<CefBrowser> browser,
CefScreenInfo& screen_info) OVERRIDE;
virtual void OnPopupShow(CefRefPtr<CefBrowser> browser,
bool show) OVERRIDE;
virtual void OnPopupSize(CefRefPtr<CefBrowser> browser,
const CefRect& rect) OVERRIDE;
virtual void OnPaint(CefRefPtr<CefBrowser> browser,
PaintElementType type,
const RectList& dirtyRects,
const void* buffer,
int width, int height) OVERRIDE;
virtual void OnCursorChange(CefRefPtr<CefBrowser> browser,
CefCursorHandle cursor) OVERRIDE;
CefWindowHandle view() { return view_; }
private:
void SetLoading(bool isLoading);
ClientOpenGLView* view_;
bool painting_popup_;
// Include the default reference counting implementation.
IMPLEMENT_REFCOUNTING(ClientOSRHandler);
};
class OSRWindow {
public:
static CefRefPtr<OSRWindow> Create(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView,
const CefRect& frame);
CefRefPtr<ClientHandler::RenderHandler> GetRenderHandler() {
return render_client.get();
}
CefWindowHandle GetWindowHandle() { return view_; }
private:
OSRWindow(OSRBrowserProvider* browser_provider,
bool transparent,
CefWindowHandle parentView,
const CefRect& frame);
~OSRWindow();
CefRefPtr<ClientOSRHandler> render_client;
CefWindowHandle view_;
IMPLEMENT_REFCOUNTING(OSRWindow);
};
#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>
<head><title>OSR Test</title></head>
<style>
.red_hover:hover {color:red;}
#li { width: 530px; }
body {background:rgba(255, 0, 0, 0.5); }
input {-webkit-appearance: none; }
#LI11select {width: 75px;}
</style>
<script>
function sendBrowserMessage(paramString) {
app.sendMessage("osrtest", [paramString]);
}
function getElement(id) { return document.getElementById(id); }
function makeH1Red() { getElement('LI00').style.color='red'; }
function makeH1Black() { getElement('LI00').style.color='black'; }
function navigate() { location.href='?k='+getElement('editbox').value; }
function load() { var select = document.getElementById('LI11select');
for (var i = 1; i < 21; i++)
select.options.add(new Option('Option ' + i, i));
}
function onEventTest(event) {
var param = event.type;
if (event.type == "click")
param += event.button;
sendBrowserMessage(param);
}
</script>
<body onfocus='onEventTest(event)' onblur='onEventTest(event)' onload='load();'>
<h1 id='LI00' onclick="onEventTest(event)">
OSR Testing h1 - Focus and blur
<select id='LI11select'>
<option value='0'>Default</option>
</select>
this page and will get this red black
</h1>
<ol>
<li id='LI01'>OnPaint should be called each time a page loads</li>
<li id='LI02' style='cursor:pointer;'><span>Move mouse
to require an OnCursorChange call</span></li>
<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>
<li id='LI04'>Right clicking will show contextual menu and will request
GetScreenPoint</li>
<li id='LI05'>IsWindowRenderingDisabled should be true</li>
<li id='LI06'>WasResized should trigger full repaint if size changes.
</li>
<li id='LI07'>Invalidate should trigger OnPaint once</li>
<li id='LI08'>Click and write here with SendKeyEvent to trigger repaints:
<input id='editbox' type='text' value='' size="5"></li>
<li id='LI09'>Click here with SendMouseClickEvent to navigate:
<input id='btnnavigate' type='button' onclick='navigate()'
value='Click here to navigate' id='editbox' /></li>
<li id='LI10' title='EXPECTED_TOOLTIP'>Mouse over this element will
trigger show a tooltip</li>
</ol>
<br />
<br />
<br />
<br />
<br />
<br />
</body>
</html>
<html>
<head><title>OSR Test</title></head>
<style>
.red_hover:hover {color:red;}
#li { width: 530px; }
body {background:rgba(255, 0, 0, 0.5); }
input {-webkit-appearance: none; }
#LI11select {width: 75px;}
</style>
<script>
function sendBrowserMessage(paramString) {
app.sendMessage("osrtest", [paramString]);
}
function getElement(id) { return document.getElementById(id); }
function makeH1Red() { getElement('LI00').style.color='red'; }
function makeH1Black() { getElement('LI00').style.color='black'; }
function navigate() { location.href='?k='+getElement('editbox').value; }
function load() { var select = document.getElementById('LI11select');
for (var i = 1; i < 21; i++)
select.options.add(new Option('Option ' + i, i));
}
function onEventTest(event) {
var param = event.type;
if (event.type == "click")
param += event.button;
sendBrowserMessage(param);
}
</script>
<body onfocus='onEventTest(event)' onblur='onEventTest(event)' onload='load();'>
<h1 id='LI00' onclick="onEventTest(event)">
OSR Testing h1 - Focus and blur
<select id='LI11select'>
<option value='0'>Default</option>
</select>
this page and will get this red black
</h1>
<ol>
<li id='LI01'>OnPaint should be called each time a page loads</li>
<li id='LI02' style='cursor:pointer;'><span>Move mouse
to require an OnCursorChange call</span></li>
<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>
<li id='LI04'>Right clicking will show contextual menu and will request
GetScreenPoint</li>
<li id='LI05'>IsWindowRenderingDisabled should be true</li>
<li id='LI06'>WasResized should trigger full repaint if size changes.
</li>
<li id='LI07'>Invalidate should trigger OnPaint once</li>
<li id='LI08'>Click and write here with SendKeyEvent to trigger repaints:
<input id='editbox' type='text' value='' size="5"></li>
<li id='LI09'>Click here with SendMouseClickEvent to navigate:
<input id='btnnavigate' type='button' onclick='navigate()'
value='Click here to navigate' id='editbox' /></li>
<li id='LI10' title='EXPECTED_TOOLTIP'>Mouse over this element will
trigger show a tooltip</li>
</ol>
<br />
<br />
<br />
<br />
<br />
<br />
</body>
</html>

View File

@ -1,29 +1,29 @@
<html>
<head>
<title>Other Tests</title>
</head>
<body>
<h3>Various other internal and external tests.</h3>
<ul>
<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://html5advent2011.digitpaint.nl/3/index.html">Cursors</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://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://html5demos.com/geo">Geolocation</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://tests/binding">JavaScript Binding</a></li>
<li><a href="http://tests/performance">JavaScript Performance Tests</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://mrdoob.com/lab/javascript/requestanimationframe/">requestAnimationFrame</a></li>
<li><a href="client://tests/handler.html">Scheme Handler</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://tests/xmlhttprequest">XMLHttpRequest</a></li>
</ul>
</body>
</html>
<html>
<head>
<title>Other Tests</title>
</head>
<body>
<h3>Various other internal and external tests.</h3>
<ul>
<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://html5advent2011.digitpaint.nl/3/index.html">Cursors</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://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://html5demos.com/geo">Geolocation</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://tests/binding">JavaScript Binding</a></li>
<li><a href="http://tests/performance">JavaScript Performance Tests</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://mrdoob.com/lab/javascript/requestanimationframe/">requestAnimationFrame</a></li>
<li><a href="client://tests/handler.html">Scheme Handler</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://tests/xmlhttprequest">XMLHttpRequest</a></li>
</ul>
</body>
</html>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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