format previously missed chromium_src .cc files

This commit is contained in:
Shelley Vohr 2018-04-17 21:57:05 -04:00
parent 8cc81509d7
commit f7d4437b3f
No known key found for this signature in database
GPG key ID: F13993A75599653C
58 changed files with 688 additions and 898 deletions

View file

@ -68,28 +68,23 @@ net::NSSCertDatabase* GetNSSCertDatabaseForResourceContext(
// callback // callback
// static // static
void CertificateManagerModel::Create( void CertificateManagerModel::Create(content::BrowserContext* browser_context,
content::BrowserContext* browser_context, const CreationCallback& callback) {
const CreationCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, BrowserThread::IO, FROM_HERE,
FROM_HERE,
base::Bind(&CertificateManagerModel::GetCertDBOnIOThread, base::Bind(&CertificateManagerModel::GetCertDBOnIOThread,
browser_context->GetResourceContext(), browser_context->GetResourceContext(), callback));
callback));
} }
CertificateManagerModel::CertificateManagerModel( CertificateManagerModel::CertificateManagerModel(
net::NSSCertDatabase* nss_cert_database, net::NSSCertDatabase* nss_cert_database,
bool is_user_db_available) bool is_user_db_available)
: cert_db_(nss_cert_database), : cert_db_(nss_cert_database), is_user_db_available_(is_user_db_available) {
is_user_db_available_(is_user_db_available) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
} }
CertificateManagerModel::~CertificateManagerModel() { CertificateManagerModel::~CertificateManagerModel() {}
}
int CertificateManagerModel::ImportFromPKCS12( int CertificateManagerModel::ImportFromPKCS12(
PK11SlotInfo* slot_info, PK11SlotInfo* slot_info,
@ -97,8 +92,8 @@ int CertificateManagerModel::ImportFromPKCS12(
const base::string16& password, const base::string16& password,
bool is_extractable, bool is_extractable,
net::ScopedCERTCertificateList* imported_certs) { net::ScopedCERTCertificateList* imported_certs) {
return cert_db_->ImportFromPKCS12(slot_info, data, password, return cert_db_->ImportFromPKCS12(slot_info, data, password, is_extractable,
is_extractable, imported_certs); imported_certs);
} }
int CertificateManagerModel::ImportUserCert(const std::string& data) { int CertificateManagerModel::ImportUserCert(const std::string& data) {
@ -116,8 +111,7 @@ bool CertificateManagerModel::ImportServerCert(
const net::ScopedCERTCertificateList& certificates, const net::ScopedCERTCertificateList& certificates,
net::NSSCertDatabase::TrustBits trust_bits, net::NSSCertDatabase::TrustBits trust_bits,
net::NSSCertDatabase::ImportCertFailureList* not_imported) { net::NSSCertDatabase::ImportCertFailureList* not_imported) {
return cert_db_->ImportServerCert(certificates, trust_bits, return cert_db_->ImportServerCert(certificates, trust_bits, not_imported);
not_imported);
} }
bool CertificateManagerModel::SetCertTrust( bool CertificateManagerModel::SetCertTrust(
@ -138,8 +132,8 @@ void CertificateManagerModel::DidGetCertDBOnUIThread(
const CreationCallback& callback) { const CreationCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::unique_ptr<CertificateManagerModel> model(new CertificateManagerModel( std::unique_ptr<CertificateManagerModel> model(
cert_db, is_user_db_available)); new CertificateManagerModel(cert_db, is_user_db_available));
callback.Run(std::move(model)); callback.Run(std::move(model));
} }
@ -151,12 +145,9 @@ void CertificateManagerModel::DidGetCertDBOnIOThread(
bool is_user_db_available = !!cert_db->GetPublicSlot(); bool is_user_db_available = !!cert_db->GetPublicSlot();
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, BrowserThread::UI, FROM_HERE,
FROM_HERE, base::Bind(&CertificateManagerModel::DidGetCertDBOnUIThread, cert_db,
base::Bind(&CertificateManagerModel::DidGetCertDBOnUIThread, is_user_db_available, callback));
cert_db,
is_user_db_available,
callback));
} }
// static // static
@ -166,8 +157,7 @@ void CertificateManagerModel::GetCertDBOnIOThread(
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);
net::NSSCertDatabase* cert_db = GetNSSCertDatabaseForResourceContext( net::NSSCertDatabase* cert_db = GetNSSCertDatabaseForResourceContext(
context, context,
base::Bind(&CertificateManagerModel::DidGetCertDBOnIOThread, base::Bind(&CertificateManagerModel::DidGetCertDBOnIOThread, callback));
callback));
if (cert_db) if (cert_db)
DidGetCertDBOnIOThread(callback, cert_db); DidGetCertDBOnIOThread(callback, cert_db);
} }

View file

@ -21,7 +21,6 @@
#include "base/win/win_util.h" #include "base/win/win_util.h"
#include "base/win/windows_version.h" #include "base/win/windows_version.h"
namespace { namespace {
int timeout_in_milliseconds = 20 * 1000; int timeout_in_milliseconds = 20 * 1000;

View file

@ -23,7 +23,8 @@ GlobalShortcutListener::~GlobalShortcutListener() {
} }
bool GlobalShortcutListener::RegisterAccelerator( bool GlobalShortcutListener::RegisterAccelerator(
const ui::Accelerator& accelerator, Observer* observer) { const ui::Accelerator& accelerator,
Observer* observer) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (IsShortcutHandlingSuspended()) if (IsShortcutHandlingSuspended())
return false; return false;
@ -48,7 +49,8 @@ bool GlobalShortcutListener::RegisterAccelerator(
} }
void GlobalShortcutListener::UnregisterAccelerator( void GlobalShortcutListener::UnregisterAccelerator(
const ui::Accelerator& accelerator, Observer* observer) { const ui::Accelerator& accelerator,
Observer* observer) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (IsShortcutHandlingSuspended()) if (IsShortcutHandlingSuspended())
return; return;
@ -88,8 +90,7 @@ void GlobalShortcutListener::SetShortcutHandlingSuspended(bool suspended) {
shortcut_handling_suspended_ = suspended; shortcut_handling_suspended_ = suspended;
for (AcceleratorMap::iterator it = accelerator_map_.begin(); for (AcceleratorMap::iterator it = accelerator_map_.begin();
it != accelerator_map_.end(); it != accelerator_map_.end(); ++it) {
++it) {
// On Linux, when shortcut handling is suspended we cannot simply early // On Linux, when shortcut handling is suspended we cannot simply early
// return in NotifyKeyPressed (similar to what we do for non-global // return in NotifyKeyPressed (similar to what we do for non-global
// shortcuts) because we'd eat the keyboard event thereby preventing the // shortcuts) because we'd eat the keyboard event thereby preventing the

View file

@ -20,13 +20,11 @@ namespace extensions {
// static // static
GlobalShortcutListener* GlobalShortcutListener::GetInstance() { GlobalShortcutListener* GlobalShortcutListener::GetInstance() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
static GlobalShortcutListenerWin* instance = static GlobalShortcutListenerWin* instance = new GlobalShortcutListenerWin();
new GlobalShortcutListenerWin();
return instance; return instance;
} }
GlobalShortcutListenerWin::GlobalShortcutListenerWin() GlobalShortcutListenerWin::GlobalShortcutListenerWin() : is_listening_(false) {
: is_listening_(false) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
} }
@ -36,17 +34,16 @@ GlobalShortcutListenerWin::~GlobalShortcutListenerWin() {
} }
void GlobalShortcutListenerWin::StartListening() { void GlobalShortcutListenerWin::StartListening() {
DCHECK(!is_listening_); // Don't start twice. DCHECK(!is_listening_); // Don't start twice.
DCHECK(!hotkey_ids_.empty()); // Also don't start if no hotkey is registered. DCHECK(!hotkey_ids_.empty()); // Also don't start if no hotkey is registered.
singleton_hwnd_observer_.reset(new gfx::SingletonHwndObserver( singleton_hwnd_observer_.reset(new gfx::SingletonHwndObserver(base::Bind(
base::Bind( &GlobalShortcutListenerWin::OnWndProc, base::Unretained(this))));
&GlobalShortcutListenerWin::OnWndProc, base::Unretained(this))));
is_listening_ = true; is_listening_ = true;
} }
void GlobalShortcutListenerWin::StopListening() { void GlobalShortcutListenerWin::StopListening() {
DCHECK(is_listening_); // No point if we are not already listening. DCHECK(is_listening_); // No point if we are not already listening.
DCHECK(hotkey_ids_.empty()); // Make sure the map is clean before ending. DCHECK(hotkey_ids_.empty()); // Make sure the map is clean before ending.
singleton_hwnd_observer_.reset(nullptr); singleton_hwnd_observer_.reset(nullptr);
is_listening_ = false; is_listening_ = false;
@ -66,8 +63,8 @@ void GlobalShortcutListenerWin::OnWndProc(HWND hwnd,
modifiers |= (LOWORD(lparam) & MOD_CONTROL) ? ui::EF_CONTROL_DOWN : 0; modifiers |= (LOWORD(lparam) & MOD_CONTROL) ? ui::EF_CONTROL_DOWN : 0;
modifiers |= (LOWORD(lparam) & MOD_WIN) ? ui::EF_COMMAND_DOWN : 0; modifiers |= (LOWORD(lparam) & MOD_WIN) ? ui::EF_COMMAND_DOWN : 0;
ui::Accelerator accelerator( ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(key_code),
ui::KeyboardCodeForWindowsKeyCode(key_code), modifiers); modifiers);
NotifyKeyPressed(accelerator); NotifyKeyPressed(accelerator);
} }
@ -83,11 +80,8 @@ bool GlobalShortcutListenerWin::RegisterAcceleratorImpl(
modifiers |= accelerator.IsCmdDown() ? MOD_WIN : 0; modifiers |= accelerator.IsCmdDown() ? MOD_WIN : 0;
static int hotkey_id = 0; static int hotkey_id = 0;
bool success = !!RegisterHotKey( bool success = !!RegisterHotKey(gfx::SingletonHwnd::GetInstance()->hwnd(),
gfx::SingletonHwnd::GetInstance()->hwnd(), hotkey_id, modifiers, accelerator.key_code());
hotkey_id,
modifiers,
accelerator.key_code());
if (!success) { if (!success) {
// Most likely error: 1409 (Hotkey already registered). // Most likely error: 1409 (Hotkey already registered).
@ -103,8 +97,8 @@ void GlobalShortcutListenerWin::UnregisterAcceleratorImpl(
HotkeyIdMap::iterator it = hotkey_ids_.find(accelerator); HotkeyIdMap::iterator it = hotkey_ids_.find(accelerator);
DCHECK(it != hotkey_ids_.end()); DCHECK(it != hotkey_ids_.end());
bool success = !!UnregisterHotKey( bool success =
gfx::SingletonHwnd::GetInstance()->hwnd(), it->second); !!UnregisterHotKey(gfx::SingletonHwnd::GetInstance()->hwnd(), it->second);
// This call should always succeed, as long as we pass in the right HWND and // This call should always succeed, as long as we pass in the right HWND and
// an id we've used to register before. // an id we've used to register before.
DCHECK(success); DCHECK(success);

View file

@ -22,16 +22,14 @@ namespace {
// exact modifiers, we need to grab all key combination including zero or more // exact modifiers, we need to grab all key combination including zero or more
// of the following: Num lock, Caps lock and Scroll lock. So that we can make // of the following: Num lock, Caps lock and Scroll lock. So that we can make
// sure the behavior of global shortcuts is consistent on all platforms. // sure the behavior of global shortcuts is consistent on all platforms.
const unsigned int kModifiersMasks[] = { const unsigned int kModifiersMasks[] = {0, // No additional modifier.
0, // No additional modifier. Mod2Mask, // Num lock
Mod2Mask, // Num lock LockMask, // Caps lock
LockMask, // Caps lock Mod5Mask, // Scroll lock
Mod5Mask, // Scroll lock Mod2Mask | LockMask,
Mod2Mask | LockMask, Mod2Mask | Mod5Mask,
Mod2Mask | Mod5Mask, LockMask | Mod5Mask,
LockMask | Mod5Mask, Mod2Mask | LockMask | Mod5Mask};
Mod2Mask | LockMask | Mod5Mask
};
int GetNativeModifiers(const ui::Accelerator& accelerator) { int GetNativeModifiers(const ui::Accelerator& accelerator) {
int modifiers = 0; int modifiers = 0;
@ -50,8 +48,7 @@ namespace extensions {
// static // static
GlobalShortcutListener* GlobalShortcutListener::GetInstance() { GlobalShortcutListener* GlobalShortcutListener::GetInstance() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
static GlobalShortcutListenerX11* instance = static GlobalShortcutListenerX11* instance = new GlobalShortcutListenerX11();
new GlobalShortcutListenerX11();
return instance; return instance;
} }
@ -68,7 +65,7 @@ GlobalShortcutListenerX11::~GlobalShortcutListenerX11() {
} }
void GlobalShortcutListenerX11::StartListening() { void GlobalShortcutListenerX11::StartListening() {
DCHECK(!is_listening_); // Don't start twice. DCHECK(!is_listening_); // Don't start twice.
DCHECK(!registered_hot_keys_.empty()); // Also don't start if no hotkey is DCHECK(!registered_hot_keys_.empty()); // Also don't start if no hotkey is
// registered. // registered.
@ -105,8 +102,8 @@ bool GlobalShortcutListenerX11::RegisterAcceleratorImpl(
DCHECK(registered_hot_keys_.find(accelerator) == registered_hot_keys_.end()); DCHECK(registered_hot_keys_.find(accelerator) == registered_hot_keys_.end());
int modifiers = GetNativeModifiers(accelerator); int modifiers = GetNativeModifiers(accelerator);
KeyCode keycode = XKeysymToKeycode(x_display_, KeyCode keycode = XKeysymToKeycode(
XKeysymForWindowsKeyCode(accelerator.key_code(), false)); x_display_, XKeysymForWindowsKeyCode(accelerator.key_code(), false));
gfx::X11ErrorTracker err_tracker; gfx::X11ErrorTracker err_tracker;
// Because XGrabKey only works on the exact modifiers mask, we should register // Because XGrabKey only works on the exact modifiers mask, we should register
@ -136,8 +133,8 @@ void GlobalShortcutListenerX11::UnregisterAcceleratorImpl(
DCHECK(registered_hot_keys_.find(accelerator) != registered_hot_keys_.end()); DCHECK(registered_hot_keys_.find(accelerator) != registered_hot_keys_.end());
int modifiers = GetNativeModifiers(accelerator); int modifiers = GetNativeModifiers(accelerator);
KeyCode keycode = XKeysymToKeycode(x_display_, KeyCode keycode = XKeysymToKeycode(
XKeysymForWindowsKeyCode(accelerator.key_code(), false)); x_display_, XKeysymForWindowsKeyCode(accelerator.key_code(), false));
for (size_t i = 0; i < arraysize(kModifiersMasks); ++i) { for (size_t i = 0; i < arraysize(kModifiersMasks); ++i) {
XUngrabKey(x_display_, keycode, modifiers | kModifiersMasks[i], XUngrabKey(x_display_, keycode, modifiers | kModifiersMasks[i],
@ -152,10 +149,10 @@ void GlobalShortcutListenerX11::OnXKeyPressEvent(::XEvent* x_event) {
modifiers |= (x_event->xkey.state & ShiftMask) ? ui::EF_SHIFT_DOWN : 0; modifiers |= (x_event->xkey.state & ShiftMask) ? ui::EF_SHIFT_DOWN : 0;
modifiers |= (x_event->xkey.state & ControlMask) ? ui::EF_CONTROL_DOWN : 0; modifiers |= (x_event->xkey.state & ControlMask) ? ui::EF_CONTROL_DOWN : 0;
modifiers |= (x_event->xkey.state & Mod1Mask) ? ui::EF_ALT_DOWN : 0; modifiers |= (x_event->xkey.state & Mod1Mask) ? ui::EF_ALT_DOWN : 0;
modifiers |= (x_event->xkey.state & Mod4Mask) ? ui::EF_COMMAND_DOWN: 0; modifiers |= (x_event->xkey.state & Mod4Mask) ? ui::EF_COMMAND_DOWN : 0;
ui::Accelerator accelerator( ui::Accelerator accelerator(ui::KeyboardCodeFromXKeyEvent(x_event),
ui::KeyboardCodeFromXKeyEvent(x_event), modifiers); modifiers);
if (registered_hot_keys_.find(accelerator) != registered_hot_keys_.end()) if (registered_hot_keys_.find(accelerator) != registered_hot_keys_.end())
NotifyKeyPressed(accelerator); NotifyKeyPressed(accelerator);
} }

View file

@ -4,11 +4,11 @@
#include <utility> #include <utility>
#include "chrome/browser/icon_loader.h"
#include "base/bind.h" #include "base/bind.h"
#include "base/task_scheduler/post_task.h" #include "base/task_scheduler/post_task.h"
#include "base/task_scheduler/task_traits.h" #include "base/task_scheduler/task_traits.h"
#include "base/threading/thread_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/icon_loader.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
using content::BrowserThread; using content::BrowserThread;

View file

@ -20,7 +20,7 @@ scoped_refptr<base::TaskRunner> IconLoader::GetReadIconTaskRunner() {
// ReadIcon() calls into views::LinuxUI and GTK2 code, so it must be on the UI // ReadIcon() calls into views::LinuxUI and GTK2 code, so it must be on the UI
// thread. // thread.
return content::BrowserThread::GetTaskRunnerForThread( return content::BrowserThread::GetTaskRunnerForThread(
content::BrowserThread::UI); content::BrowserThread::UI);
} }
void IconLoader::ReadIcon() { void IconLoader::ReadIcon() {

View file

@ -4,8 +4,8 @@
#include "chrome/browser/icon_loader.h" #include "chrome/browser/icon_loader.h"
#include <windows.h>
#include <shellapi.h> #include <shellapi.h>
#include <windows.h>
#include "base/bind.h" #include "base/bind.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
@ -54,15 +54,15 @@ void IconLoader::ReadIcon() {
std::unique_ptr<gfx::Image> image; std::unique_ptr<gfx::Image> image;
SHFILEINFO file_info = { 0 }; SHFILEINFO file_info = {0};
if (SHGetFileInfo(group_.c_str(), FILE_ATTRIBUTE_NORMAL, &file_info, if (SHGetFileInfo(group_.c_str(), FILE_ATTRIBUTE_NORMAL, &file_info,
sizeof(SHFILEINFO), sizeof(SHFILEINFO),
SHGFI_ICON | size | SHGFI_USEFILEATTRIBUTES)) { SHGFI_ICON | size | SHGFI_USEFILEATTRIBUTES)) {
std::unique_ptr<SkBitmap> bitmap( std::unique_ptr<SkBitmap> bitmap(
IconUtil::CreateSkBitmapFromHICON(file_info.hIcon)); IconUtil::CreateSkBitmapFromHICON(file_info.hIcon));
if (bitmap.get()) { if (bitmap.get()) {
gfx::ImageSkia image_skia(gfx::ImageSkiaRep(*bitmap, gfx::ImageSkia image_skia(
display::win::GetDPIScale())); gfx::ImageSkiaRep(*bitmap, display::win::GetDPIScale()));
image_skia.MakeThreadSafe(); image_skia.MakeThreadSafe();
image = std::make_unique<gfx::Image>(image_skia); image = std::make_unique<gfx::Image>(image_skia);
DestroyIcon(file_info.hIcon); DestroyIcon(file_info.hIcon);

View file

@ -27,8 +27,7 @@ void RunCallbackIfNotCanceled(
IconManager::IconManager() : weak_factory_(this) {} IconManager::IconManager() : weak_factory_(this) {}
IconManager::~IconManager() { IconManager::~IconManager() {}
}
gfx::Image* IconManager::LookupIconFromFilepath(const base::FilePath& file_path, gfx::Image* IconManager::LookupIconFromFilepath(const base::FilePath& file_path,
IconLoader::IconSize size) { IconLoader::IconSize size) {
@ -52,8 +51,8 @@ base::CancelableTaskTracker::TaskId IconManager::LoadIcon(
base::CancelableTaskTracker::IsCanceledCallback is_canceled; base::CancelableTaskTracker::IsCanceledCallback is_canceled;
base::CancelableTaskTracker::TaskId id = base::CancelableTaskTracker::TaskId id =
tracker->NewTrackedTaskId(&is_canceled); tracker->NewTrackedTaskId(&is_canceled);
IconRequestCallback callback_runner = base::Bind( IconRequestCallback callback_runner =
&RunCallbackIfNotCanceled, is_canceled, callback); base::Bind(&RunCallbackIfNotCanceled, is_canceled, callback);
IconLoader* loader = IconLoader::Create( IconLoader* loader = IconLoader::Create(
file_path, size, file_path, size,
@ -88,6 +87,6 @@ IconManager::CacheKey::CacheKey(const IconLoader::IconGroup& group,
IconLoader::IconSize size) IconLoader::IconSize size)
: group(group), size(size) {} : group(group), size(size) {}
bool IconManager::CacheKey::operator<(const CacheKey &other) const { bool IconManager::CacheKey::operator<(const CacheKey& other) const {
return std::tie(group, size) < std::tie(other.group, other.size); return std::tie(group, size) < std::tie(other.group, other.size);
} }

View file

@ -20,8 +20,8 @@ using base::PlatformThreadRef;
#include "media/base/video_util.h" #include "media/base/video_util.h"
#include "third_party/libyuv/include/libyuv/scale_argb.h" #include "third_party/libyuv/include/libyuv/scale_argb.h"
#include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/skia_util.h" #include "ui/gfx/skia_util.h"
@ -50,9 +50,8 @@ gfx::ImageSkia ScaleDesktopFrame(std::unique_ptr<webrtc::DesktopFrame> frame,
result.allocN32Pixels(scaled_rect.width(), scaled_rect.height(), true); result.allocN32Pixels(scaled_rect.width(), scaled_rect.height(), true);
uint8* pixels_data = reinterpret_cast<uint8*>(result.getPixels()); uint8* pixels_data = reinterpret_cast<uint8*>(result.getPixels());
libyuv::ARGBScale(frame->data(), frame->stride(), libyuv::ARGBScale(frame->data(), frame->stride(), frame->size().width(),
frame->size().width(), frame->size().height(), frame->size().height(), pixels_data, result.rowBytes(),
pixels_data, result.rowBytes(),
scaled_rect.width(), scaled_rect.height(), scaled_rect.width(), scaled_rect.height(),
libyuv::kFilterBilinear); libyuv::kFilterBilinear);
@ -76,9 +75,7 @@ gfx::ImageSkia ScaleDesktopFrame(std::unique_ptr<webrtc::DesktopFrame> frame,
NativeDesktopMediaList::SourceDescription::SourceDescription( NativeDesktopMediaList::SourceDescription::SourceDescription(
DesktopMediaID id, DesktopMediaID id,
const base::string16& name) const base::string16& name)
: id(id), : id(id), name(name) {}
name(name) {
}
class NativeDesktopMediaList::Worker class NativeDesktopMediaList::Worker
: public webrtc::DesktopCapturer::Callback { : public webrtc::DesktopCapturer::Callback {
@ -137,12 +134,12 @@ void NativeDesktopMediaList::Worker::Refresh(
base::string16 title; base::string16 title;
for (size_t i = 0; i < screens.size(); ++i) { for (size_t i = 0; i < screens.size(); ++i) {
if (mutiple_screens) { if (mutiple_screens) {
title = base::UTF8ToUTF16("Screen " + base::IntToString(i+1)); title = base::UTF8ToUTF16("Screen " + base::IntToString(i + 1));
} else { } else {
title = base::UTF8ToUTF16("Entire screen"); title = base::UTF8ToUTF16("Entire screen");
} }
sources.push_back(SourceDescription(DesktopMediaID( sources.push_back(SourceDescription(
DesktopMediaID::TYPE_SCREEN, screens[i].id), title)); DesktopMediaID(DesktopMediaID::TYPE_SCREEN, screens[i].id), title));
} }
} }
} }
@ -163,8 +160,7 @@ void NativeDesktopMediaList::Worker::Refresh(
// Update list of windows before updating thumbnails. // Update list of windows before updating thumbnails.
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourcesList, base::Bind(&NativeDesktopMediaList::OnSourcesList, media_list_, sources));
media_list_, sources));
ImageHashesMap new_image_hashes; ImageHashesMap new_image_hashes;
@ -202,8 +198,8 @@ void NativeDesktopMediaList::Worker::Refresh(
ScaleDesktopFrame(std::move(current_frame_), thumbnail_size); ScaleDesktopFrame(std::move(current_frame_), thumbnail_size);
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
base::Bind(&NativeDesktopMediaList::OnSourceThumbnail, base::Bind(&NativeDesktopMediaList::OnSourceThumbnail, media_list_,
media_list_, i, thumbnail)); i, thumbnail));
} }
} }
} }
@ -248,8 +244,7 @@ void NativeDesktopMediaList::SetUpdatePeriod(base::TimeDelta period) {
update_period_ = period; update_period_ = period;
} }
void NativeDesktopMediaList::SetThumbnailSize( void NativeDesktopMediaList::SetThumbnailSize(const gfx::Size& thumbnail_size) {
const gfx::Size& thumbnail_size) {
thumbnail_size_ = thumbnail_size; thumbnail_size_ = thumbnail_size;
} }
@ -279,7 +274,8 @@ const DesktopMediaList::Source& NativeDesktopMediaList::GetSource(
return sources_[index]; return sources_[index];
} }
std::vector<DesktopMediaList::Source> NativeDesktopMediaList::GetSources() const { std::vector<DesktopMediaList::Source> NativeDesktopMediaList::GetSources()
const {
return sources_; return sources_;
} }
@ -351,9 +347,8 @@ void NativeDesktopMediaList::OnSourcesList(
} }
} }
void NativeDesktopMediaList::OnSourceThumbnail( void NativeDesktopMediaList::OnSourceThumbnail(int index,
int index, const gfx::ImageSkia& image) {
const gfx::ImageSkia& image) {
DCHECK_LT(index, static_cast<int>(sources_.size())); DCHECK_LT(index, static_cast<int>(sources_.size()));
sources_[index].thumbnail = image; sources_[index].thumbnail = image;
observer_->OnSourceThumbnailChanged(index); observer_->OnSourceThumbnailChanged(index);
@ -363,10 +358,9 @@ void NativeDesktopMediaList::OnRefreshFinished() {
// Give a chance to the observer to stop the refresh work. // Give a chance to the observer to stop the refresh work.
bool is_continue = observer_->OnRefreshFinished(); bool is_continue = observer_->OnRefreshFinished();
if (is_continue) { if (is_continue) {
BrowserThread::PostDelayedTask( BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
BrowserThread::UI, FROM_HERE, base::Bind(&NativeDesktopMediaList::Refresh,
base::Bind(&NativeDesktopMediaList::Refresh, weak_factory_.GetWeakPtr()),
weak_factory_.GetWeakPtr()), update_period_);
update_period_);
} }
} }

View file

@ -223,8 +223,8 @@ class PdfConverterUtilityProcessHostClient
std::unique_ptr<MetafilePlayer> std::unique_ptr<MetafilePlayer>
PdfConverterUtilityProcessHostClient::GetFileFromTemp( PdfConverterUtilityProcessHostClient::GetFileFromTemp(
std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread> std::unique_ptr<base::File, content::BrowserThread::DeleteOnFileThread>
temp_file) { temp_file) {
if (settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2 || if (settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2 ||
settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3) { settings_.mode == PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3) {
return std::make_unique<PostScriptMetaFile>(temp_dir_, return std::make_unique<PostScriptMetaFile>(temp_dir_,
@ -278,12 +278,10 @@ ScopedTempFile CreateTempFile(scoped_refptr<RefCountedTempDir>* temp_dir) {
<< (*temp_dir)->GetPath().value(); << (*temp_dir)->GetPath().value();
return file; return file;
} }
file.reset(new base::File(path, file.reset(new base::File(
base::File::FLAG_CREATE_ALWAYS | path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE |
base::File::FLAG_WRITE | base::File::FLAG_READ | base::File::FLAG_DELETE_ON_CLOSE |
base::File::FLAG_READ | base::File::FLAG_TEMPORARY));
base::File::FLAG_DELETE_ON_CLOSE |
base::File::FLAG_TEMPORARY));
if (!file->IsValid()) { if (!file->IsValid()) {
PLOG(ERROR) << "Failed to create " << path.value(); PLOG(ERROR) << "Failed to create " << path.value();
file.reset(); file.reset();
@ -344,8 +342,7 @@ bool LazyEmf::LoadEmf(Emf* emf) const {
return emf->InitFromData(data.data(), data.size()); return emf->InitFromData(data.data(), data.size());
} }
PostScriptMetaFile::~PostScriptMetaFile() { PostScriptMetaFile::~PostScriptMetaFile() {}
}
bool PostScriptMetaFile::SafePlayback(HDC hdc) const { bool PostScriptMetaFile::SafePlayback(HDC hdc) const {
// TODO(thestig): Fix destruction of metafiles. For some reasons // TODO(thestig): Fix destruction of metafiles. For some reasons
@ -526,7 +523,6 @@ void PdfConverterUtilityProcessHostClient::OnFailed() {
utility_process_host_.reset(); utility_process_host_.reset();
} }
void PdfConverterUtilityProcessHostClient::OnPreCacheFontCharacters( void PdfConverterUtilityProcessHostClient::OnPreCacheFontCharacters(
const LOGFONT& font, const LOGFONT& font,
const base::string16& str) { const base::string16& str) {
@ -603,12 +599,12 @@ PdfConverterImpl::~PdfConverterImpl() {
} }
void PdfConverterImpl::Start( void PdfConverterImpl::Start(
const scoped_refptr<PdfConverterUtilityProcessHostClient>& utility_client, const scoped_refptr<PdfConverterUtilityProcessHostClient>& utility_client,
const scoped_refptr<base::RefCountedMemory>& data, const scoped_refptr<base::RefCountedMemory>& data,
const StartCallback& start_callback) { const StartCallback& start_callback) {
DCHECK(!utility_client_); DCHECK(!utility_client_);
utility_client_ = utility_client; utility_client_ = utility_client;
utility_client_->Start(data, start_callback); utility_client_->Start(data, start_callback);
} }
void PdfConverterImpl::GetPage(int page_number, void PdfConverterImpl::GetPage(int page_number,
@ -632,10 +628,9 @@ std::unique_ptr<PdfConverter> PdfConverter::StartPdfConverter(
const StartCallback& start_callback) { const StartCallback& start_callback) {
std::unique_ptr<PdfConverterImpl> converter = std::unique_ptr<PdfConverterImpl> converter =
std::make_unique<PdfConverterImpl>(); std::make_unique<PdfConverterImpl>();
converter->Start( converter->Start(new PdfConverterUtilityProcessHostClient(
new PdfConverterUtilityProcessHostClient(converter->GetWeakPtr(), converter->GetWeakPtr(), conversion_settings),
conversion_settings), data, start_callback);
data, start_callback);
return std::move(converter); return std::move(converter);
} }

View file

@ -12,8 +12,8 @@
#include "base/location.h" #include "base/location.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/task_scheduler/post_task.h"
#include "base/single_thread_task_runner.h" #include "base/single_thread_task_runner.h"
#include "base/task_scheduler/post_task.h"
#include "base/threading/sequenced_worker_pool.h" #include "base/threading/sequenced_worker_pool.h"
#include "base/threading/thread_restrictions.h" #include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h"
@ -44,9 +44,7 @@ void HoldRefCallback(const scoped_refptr<PrintJobWorkerOwner>& owner,
} // namespace } // namespace
PrintJob::PrintJob() PrintJob::PrintJob()
: is_job_pending_(false), : is_job_pending_(false), is_canceling_(false), quit_factory_(this) {
is_canceling_(false),
quit_factory_(this) {
// This is normally a UI message loop, but in unit tests, the message loop is // This is normally a UI message loop, but in unit tests, the message loop is
// of the 'default' type. // of the 'default' type.
DCHECK(base::MessageLoopForUI::IsCurrent() || DCHECK(base::MessageLoopForUI::IsCurrent() ||
@ -133,8 +131,7 @@ void PrintJob::StartPrinting() {
scoped_refptr<JobEventDetails> details( scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), nullptr)); new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), nullptr));
content::NotificationService::current()->Notify( content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this),
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get())); content::Details<JobEventDetails>(details.get()));
} }
@ -178,8 +175,7 @@ void PrintJob::Cancel() {
scoped_refptr<JobEventDetails> details( scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::FAILED, nullptr, nullptr)); new JobEventDetails(JobEventDetails::FAILED, nullptr, nullptr));
content::NotificationService::current()->Notify( content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this),
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get())); content::Details<JobEventDetails>(details.get()));
Stop(); Stop();
is_canceling_ = false; is_canceling_ = false;
@ -221,8 +217,8 @@ class PrintJob::PdfConversionState {
void Start(const scoped_refptr<base::RefCountedMemory>& data, void Start(const scoped_refptr<base::RefCountedMemory>& data,
const PdfRenderSettings& conversion_settings, const PdfRenderSettings& conversion_settings,
const PdfConverter::StartCallback& start_callback) { const PdfConverter::StartCallback& start_callback) {
converter_ = PdfConverter::StartPdfConverter( converter_ = PdfConverter::StartPdfConverter(data, conversion_settings,
data, conversion_settings, start_callback); start_callback);
} }
void GetMorePages(const PdfConverter::GetPageCallback& get_page_callback) { void GetMorePages(const PdfConverter::GetPageCallback& get_page_callback) {
@ -313,8 +309,8 @@ void PrintJob::StartPdfToPostScriptConversion(
const gfx::Point& physical_offsets, const gfx::Point& physical_offsets,
bool ps_level2) { bool ps_level2) {
DCHECK(!pdf_conversion_state_); DCHECK(!pdf_conversion_state_);
pdf_conversion_state_ = std::make_unique<PdfConversionState>( pdf_conversion_state_ =
gfx::Size(), gfx::Rect()); std::make_unique<PdfConversionState>(gfx::Size(), gfx::Rect());
const int kPrinterDpi = settings().dpi(); const int kPrinterDpi = settings().dpi();
PdfRenderSettings settings( PdfRenderSettings settings(
content_area, physical_offsets, kPrinterDpi, true /* autorotate? */, content_area, physical_offsets, kPrinterDpi, true /* autorotate? */,
@ -399,8 +395,7 @@ void PrintJob::OnDocumentDone() {
scoped_refptr<JobEventDetails> details( scoped_refptr<JobEventDetails> details(
new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), nullptr)); new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), nullptr));
content::NotificationService::current()->Notify( content::NotificationService::current()->Notify(
chrome::NOTIFICATION_PRINT_JOB_EVENT, chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this),
content::Source<PrintJob>(this),
content::Details<JobEventDetails>(details.get())); content::Details<JobEventDetails>(details.get()));
} }
@ -431,7 +426,6 @@ void PrintJob::ControlledWorkerShutdown() {
} }
#endif #endif
// Now make sure the thread object is cleaned up. Do this on a worker // Now make sure the thread object is cleaned up. Do this on a worker
// thread because it may block. // thread because it may block.
base::PostTaskAndReply( base::PostTaskAndReply(
@ -444,8 +438,7 @@ void PrintJob::ControlledWorkerShutdown() {
UpdatePrintedDocument(nullptr); UpdatePrintedDocument(nullptr);
} }
void PrintJob::HoldUntilStopIsCalled() { void PrintJob::HoldUntilStopIsCalled() {}
}
void PrintJob::Quit() { void PrintJob::Quit() {
base::RunLoop::QuitCurrentWhenIdleDeprecated(); base::RunLoop::QuitCurrentWhenIdleDeprecated();
@ -455,16 +448,16 @@ void PrintJob::Quit() {
JobEventDetails::JobEventDetails(Type type, JobEventDetails::JobEventDetails(Type type,
PrintedDocument* document, PrintedDocument* document,
PrintedPage* page) PrintedPage* page)
: document_(document), : document_(document), page_(page), type_(type) {}
page_(page),
type_(type) { JobEventDetails::~JobEventDetails() {}
PrintedDocument* JobEventDetails::document() const {
return document_.get();
} }
JobEventDetails::~JobEventDetails() { PrintedPage* JobEventDetails::page() const {
return page_.get();
} }
PrintedDocument* JobEventDetails::document() const { return document_.get(); }
PrintedPage* JobEventDetails::page() const { return page_.get(); }
} // namespace printing } // namespace printing

View file

@ -14,8 +14,7 @@
namespace printing { namespace printing {
PrintQueriesQueue::PrintQueriesQueue() { PrintQueriesQueue::PrintQueriesQueue() {}
}
PrintQueriesQueue::~PrintQueriesQueue() { PrintQueriesQueue::~PrintQueriesQueue() {
base::AutoLock lock(lock_); base::AutoLock lock(lock_);
@ -47,8 +46,7 @@ scoped_refptr<PrinterQuery> PrintQueriesQueue::PopPrinterQuery(
scoped_refptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery( scoped_refptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery(
int render_process_id, int render_process_id,
int render_frame_id) { int render_frame_id) {
return WrapRefCounted( return WrapRefCounted(new PrinterQuery(render_process_id, render_frame_id));
new PrinterQuery(render_process_id, render_frame_id));
} }
void PrintQueriesQueue::Shutdown() { void PrintQueriesQueue::Shutdown() {
@ -71,8 +69,7 @@ PrintJobManager::PrintJobManager() : is_shutdown_(false) {
content::NotificationService::AllSources()); content::NotificationService::AllSources());
} }
PrintJobManager::~PrintJobManager() { PrintJobManager::~PrintJobManager() {}
}
scoped_refptr<PrintQueriesQueue> PrintJobManager::queue() { scoped_refptr<PrintQueriesQueue> PrintJobManager::queue() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@ -117,9 +114,8 @@ void PrintJobManager::Observe(int type,
*content::Details<JobEventDetails>(details).ptr()); *content::Details<JobEventDetails>(details).ptr());
} }
void PrintJobManager::OnPrintJobEvent( void PrintJobManager::OnPrintJobEvent(PrintJob* print_job,
PrintJob* print_job, const JobEventDetails& event_details) {
const JobEventDetails& event_details) {
switch (event_details.type()) { switch (event_details.type()) {
case JobEventDetails::NEW_DOC: { case JobEventDetails::NEW_DOC: {
DCHECK(current_jobs_.end() == current_jobs_.find(print_job)); DCHECK(current_jobs_.end() == current_jobs_.find(print_job));

View file

@ -57,11 +57,14 @@ void HoldRefCallback(const scoped_refptr<PrintJobWorkerOwner>& owner,
void SetCustomMarginsToJobSettings(const PageSizeMargins& page_size_margins, void SetCustomMarginsToJobSettings(const PageSizeMargins& page_size_margins,
base::DictionaryValue* settings) { base::DictionaryValue* settings) {
std::unique_ptr<base::DictionaryValue> custom_margins(new base::DictionaryValue()); std::unique_ptr<base::DictionaryValue> custom_margins(
new base::DictionaryValue());
custom_margins->SetDouble(kSettingMarginTop, page_size_margins.margin_top); custom_margins->SetDouble(kSettingMarginTop, page_size_margins.margin_top);
custom_margins->SetDouble(kSettingMarginBottom, page_size_margins.margin_bottom); custom_margins->SetDouble(kSettingMarginBottom,
page_size_margins.margin_bottom);
custom_margins->SetDouble(kSettingMarginLeft, page_size_margins.margin_left); custom_margins->SetDouble(kSettingMarginLeft, page_size_margins.margin_left);
custom_margins->SetDouble(kSettingMarginRight, page_size_margins.margin_right); custom_margins->SetDouble(kSettingMarginRight,
page_size_margins.margin_right);
settings->Set(kSettingMarginsCustom, std::move(custom_margins)); settings->Set(kSettingMarginsCustom, std::move(custom_margins));
} }
@ -83,7 +86,8 @@ void PrintSettingsToJobSettings(const PrintSettings& settings,
auto margin_type = settings.margin_type(); auto margin_type = settings.margin_type();
job_settings->SetInteger(kSettingMarginsType, settings.margin_type()); job_settings->SetInteger(kSettingMarginsType, settings.margin_type());
if (margin_type == CUSTOM_MARGINS) { if (margin_type == CUSTOM_MARGINS) {
const auto& margins_in_points = settings.requested_custom_margins_in_points(); const auto& margins_in_points =
settings.requested_custom_margins_in_points();
PageSizeMargins page_size_margins; PageSizeMargins page_size_margins;
@ -130,7 +134,6 @@ void PrintSettingsToJobSettings(const PrintSettings& settings,
job_settings->SetInteger(kSettingPreviewPageCount, 1); job_settings->SetInteger(kSettingPreviewPageCount, 1);
} }
class PrintingContextDelegate : public PrintingContext::Delegate { class PrintingContextDelegate : public PrintingContext::Delegate {
public: public:
PrintingContextDelegate(int render_process_id, int render_frame_id); PrintingContextDelegate(int render_process_id, int render_frame_id);
@ -152,8 +155,7 @@ PrintingContextDelegate::PrintingContextDelegate(int render_process_id,
: render_process_id_(render_process_id), : render_process_id_(render_process_id),
render_frame_id_(render_frame_id) {} render_frame_id_(render_frame_id) {}
PrintingContextDelegate::~PrintingContextDelegate() { PrintingContextDelegate::~PrintingContextDelegate() {}
}
gfx::NativeView PrintingContextDelegate::GetParentView() { gfx::NativeView PrintingContextDelegate::GetParentView() {
content::WebContents* wc = GetWebContents(); content::WebContents* wc = GetWebContents();
@ -243,17 +245,14 @@ void PrintJobWorker::GetSettings(bool ask_user_for_settings,
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
base::Bind(&HoldRefCallback, WrapRefCounted(owner_), base::Bind(&HoldRefCallback, WrapRefCounted(owner_),
base::Bind(&PrintJobWorker::GetSettingsWithUI, base::Bind(&PrintJobWorker::GetSettingsWithUI,
base::Unretained(this), base::Unretained(this), document_page_count,
document_page_count, has_selection, is_scripted)));
has_selection,
is_scripted)));
} else if (!device_name.empty()) { } else if (!device_name.empty()) {
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
base::Bind(&HoldRefCallback, WrapRefCounted(owner_), base::Bind(&HoldRefCallback, WrapRefCounted(owner_),
base::Bind(&PrintJobWorker::InitWithDeviceName, base::Bind(&PrintJobWorker::InitWithDeviceName,
base::Unretained(this), base::Unretained(this), device_name)));
device_name)));
} else { } else {
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
@ -268,13 +267,11 @@ void PrintJobWorker::SetSettings(
DCHECK(task_runner_->RunsTasksInCurrentSequence()); DCHECK(task_runner_->RunsTasksInCurrentSequence());
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, BrowserThread::UI, FROM_HERE,
FROM_HERE, base::Bind(
base::Bind(&HoldRefCallback, &HoldRefCallback, WrapRefCounted(owner_),
WrapRefCounted(owner_), base::Bind(&PrintJobWorker::UpdatePrintSettings,
base::Bind(&PrintJobWorker::UpdatePrintSettings, base::Unretained(this), base::Passed(&new_settings))));
base::Unretained(this),
base::Passed(&new_settings))));
} }
void PrintJobWorker::UpdatePrintSettings( void PrintJobWorker::UpdatePrintSettings(
@ -296,17 +293,15 @@ void PrintJobWorker::GetSettingsDone(PrintingContext::Result result) {
// We can't use OnFailure() here since owner_ may not support notifications. // We can't use OnFailure() here since owner_ may not support notifications.
// PrintJob will create the new PrintedDocument. // PrintJob will create the new PrintedDocument.
owner_->PostTask(FROM_HERE, owner_->PostTask(
base::Bind(&PrintJobWorkerOwner::GetSettingsDone, FROM_HERE,
WrapRefCounted(owner_), base::Bind(&PrintJobWorkerOwner::GetSettingsDone, WrapRefCounted(owner_),
printing_context_->settings(), printing_context_->settings(), result));
result));
} }
void PrintJobWorker::GetSettingsWithUI( void PrintJobWorker::GetSettingsWithUI(int document_page_count,
int document_page_count, bool has_selection,
bool has_selection, bool is_scripted) {
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
// weak_factory_ creates pointers valid only on owner_ thread. // weak_factory_ creates pointers valid only on owner_ thread.

View file

@ -13,8 +13,7 @@ namespace printing {
PrintJobWorkerOwner::PrintJobWorkerOwner() PrintJobWorkerOwner::PrintJobWorkerOwner()
: task_runner_(base::ThreadTaskRunnerHandle::Get()) {} : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
PrintJobWorkerOwner::~PrintJobWorkerOwner() { PrintJobWorkerOwner::~PrintJobWorkerOwner() {}
}
bool PrintJobWorkerOwner::RunsTasksInCurrentSequence() const { bool PrintJobWorkerOwner::RunsTasksInCurrentSequence() const {
return task_runner_->RunsTasksInCurrentSequence(); return task_runner_->RunsTasksInCurrentSequence();

View file

@ -15,8 +15,8 @@
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "printing/page_size_margins.h" #include "printing/page_size_margins.h"
#include "printing/print_job_constants.h"
#include "printing/pdf_metafile_skia.h" #include "printing/pdf_metafile_skia.h"
#include "printing/print_job_constants.h"
#include "atom/common/node_includes.h" #include "atom/common/node_includes.h"
@ -35,9 +35,9 @@ void StopWorker(int document_cookie) {
scoped_refptr<printing::PrinterQuery> printer_query = scoped_refptr<printing::PrinterQuery> printer_query =
queue->PopPrinterQuery(document_cookie); queue->PopPrinterQuery(document_cookie);
if (printer_query.get()) { if (printer_query.get()) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, BrowserThread::PostTask(
base::Bind(&printing::PrinterQuery::StopWorker, BrowserThread::IO, FROM_HERE,
printer_query)); base::Bind(&printing::PrinterQuery::StopWorker, printer_query));
} }
} }
@ -61,15 +61,13 @@ void FreeNodeBufferData(char* data, void* hint) {
namespace printing { namespace printing {
PrintPreviewMessageHandler::PrintPreviewMessageHandler( PrintPreviewMessageHandler::PrintPreviewMessageHandler(
WebContents* web_contents) WebContents* web_contents)
: content::WebContentsObserver(web_contents) { : content::WebContentsObserver(web_contents) {
DCHECK(web_contents); DCHECK(web_contents);
} }
PrintPreviewMessageHandler::~PrintPreviewMessageHandler() { PrintPreviewMessageHandler::~PrintPreviewMessageHandler() {}
}
void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
const PrintHostMsg_DidPreviewDocument_Params& params) { const PrintHostMsg_DidPreviewDocument_Params& params) {
@ -82,12 +80,9 @@ void PrintPreviewMessageHandler::OnMetafileReadyForPrinting(
} }
BrowserThread::PostTaskAndReplyWithResult( BrowserThread::PostTaskAndReplyWithResult(
BrowserThread::IO, BrowserThread::IO, FROM_HERE, base::Bind(&CopyPDFDataOnIOThread, params),
FROM_HERE,
base::Bind(&CopyPDFDataOnIOThread, params),
base::Bind(&PrintPreviewMessageHandler::RunPrintToPDFCallback, base::Bind(&PrintPreviewMessageHandler::RunPrintToPDFCallback,
base::Unretained(this), base::Unretained(this), params.preview_request_id,
params.preview_request_id,
params.data_size)); params.data_size));
} }
@ -104,8 +99,7 @@ bool PrintPreviewMessageHandler::OnMessageReceived(
IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message) IPC_BEGIN_MESSAGE_MAP(PrintPreviewMessageHandler, message)
IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting, IPC_MESSAGE_HANDLER(PrintHostMsg_MetafileReadyForPrinting,
OnMetafileReadyForPrinting) OnMetafileReadyForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed, IPC_MESSAGE_HANDLER(PrintHostMsg_PrintPreviewFailed, OnPrintPreviewFailed)
OnPrintPreviewFailed)
IPC_MESSAGE_UNHANDLED(handled = false) IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP() IPC_END_MESSAGE_MAP()
return handled; return handled;
@ -122,21 +116,23 @@ void PrintPreviewMessageHandler::PrintToPDF(
rfh->Send(new PrintMsg_PrintPreview(rfh->GetRoutingID(), options)); rfh->Send(new PrintMsg_PrintPreview(rfh->GetRoutingID(), options));
} }
void PrintPreviewMessageHandler::RunPrintToPDFCallback( void PrintPreviewMessageHandler::RunPrintToPDFCallback(int request_id,
int request_id, uint32_t data_size, char* data) { uint32_t data_size,
char* data) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Locker locker(isolate); v8::Locker locker(isolate);
v8::HandleScope handle_scope(isolate); v8::HandleScope handle_scope(isolate);
if (data) { if (data) {
v8::Local<v8::Value> buffer = node::Buffer::New(isolate, v8::Local<v8::Value> buffer =
data, static_cast<size_t>(data_size), &FreeNodeBufferData, nullptr) node::Buffer::New(isolate, data, static_cast<size_t>(data_size),
.ToLocalChecked(); &FreeNodeBufferData, nullptr)
.ToLocalChecked();
print_to_pdf_callback_map_[request_id].Run(v8::Null(isolate), buffer); print_to_pdf_callback_map_[request_id].Run(v8::Null(isolate), buffer);
} else { } else {
v8::Local<v8::String> error_message = v8::String::NewFromUtf8(isolate, v8::Local<v8::String> error_message =
"Failed to generate PDF"); v8::String::NewFromUtf8(isolate, "Failed to generate PDF");
print_to_pdf_callback_map_[request_id].Run( print_to_pdf_callback_map_[request_id].Run(
v8::Exception::Error(error_message), v8::Null(isolate)); v8::Exception::Error(error_message), v8::Null(isolate));
} }

View file

@ -12,7 +12,6 @@
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h" #include "base/strings/utf_string_conversions.h"
#include "base/timer/timer.h" #include "base/timer/timer.h"
#include "components/prefs/pref_service.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job.h"
@ -22,6 +21,7 @@
#include "chrome/browser/ui/simple_message_box.h" #include "chrome/browser/ui/simple_message_box.h"
#include "chrome/common/pref_names.h" #include "chrome/common/pref_names.h"
#include "chrome/common/print_messages.h" #include "chrome/common/print_messages.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h" #include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h" #include "content/public/browser/notification_service.h"
@ -42,9 +42,7 @@ using content::BrowserThread;
namespace printing { namespace printing {
namespace { namespace {} // namespace
} // namespace
PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents), : content::WebContentsObserver(web_contents),
@ -67,12 +65,12 @@ PrintViewManagerBase::~PrintViewManagerBase() {
#if !defined(DISABLE_BASIC_PRINTING) #if !defined(DISABLE_BASIC_PRINTING)
bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh,
bool silent, bool print_background, bool silent,
bool print_background,
const base::string16& device_name) { const base::string16& device_name) {
int32_t id = rfh->GetRoutingID(); int32_t id = rfh->GetRoutingID();
return PrintNowInternal( return PrintNowInternal(rfh, std::make_unique<PrintMsg_PrintPages>(
rfh, id, silent, print_background, device_name));
std::make_unique<PrintMsg_PrintPages>(id, silent, print_background, device_name));
} }
#endif // !DISABLE_BASIC_PRINTING #endif // !DISABLE_BASIC_PRINTING
@ -114,7 +112,7 @@ void PrintViewManagerBase::OnDidGetDocumentCookie(int cookie) {
} }
void PrintViewManagerBase::OnDidPrintPage( void PrintViewManagerBase::OnDidPrintPage(
const PrintHostMsg_DidPrintPage_Params& params) { const PrintHostMsg_DidPrintPage_Params& params) {
if (!OpportunisticallyCreatePrintJob(params.document_cookie)) if (!OpportunisticallyCreatePrintJob(params.document_cookie))
return; return;
@ -153,18 +151,15 @@ void PrintViewManagerBase::OnDidPrintPage(
#if !defined(OS_WIN) #if !defined(OS_WIN)
// Update the rendered document. It will send notifications to the listener. // Update the rendered document. It will send notifications to the listener.
document->SetPage(params.page_number, document->SetPage(params.page_number, std::move(metafile), params.page_size,
std::move(metafile),
params.page_size,
params.content_area); params.content_area);
ShouldQuitFromInnerMessageLoop(); ShouldQuitFromInnerMessageLoop();
#else #else
print_job_->AppendPrintedPage(params.page_number); print_job_->AppendPrintedPage(params.page_number);
if (metafile_must_be_valid) { if (metafile_must_be_valid) {
bool print_text_with_gdi = bool print_text_with_gdi = document->settings().print_text_with_gdi() &&
document->settings().print_text_with_gdi() && !document->settings().printer_is_xps();
!document->settings().printer_is_xps();
scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes( scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes(
reinterpret_cast<const unsigned char*>(shared_buf.memory()), reinterpret_cast<const unsigned char*>(shared_buf.memory()),
@ -172,8 +167,7 @@ void PrintViewManagerBase::OnDidPrintPage(
document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf"));
print_job_->StartPdfToEmfConversion( print_job_->StartPdfToEmfConversion(
bytes, params.page_size, params.content_area, bytes, params.page_size, params.content_area, print_text_with_gdi);
print_text_with_gdi);
} }
#endif // !OS_WIN #endif // !OS_WIN
} }
@ -284,8 +278,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
return false; return false;
// We can't print if there is no renderer. // We can't print if there is no renderer.
if (!web_contents() || if (!web_contents() || !web_contents()->GetRenderViewHost() ||
!web_contents()->GetRenderViewHost() ||
!web_contents()->GetRenderViewHost()->IsRenderViewLive()) { !web_contents()->GetRenderViewHost()->IsRenderViewLive()) {
return false; return false;
} }
@ -318,8 +311,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() { void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() {
// Look at the reason. // Look at the reason.
DCHECK(print_job_->document()); DCHECK(print_job_->document());
if (print_job_->document() && if (print_job_->document() && print_job_->document()->IsComplete() &&
print_job_->document()->IsComplete() &&
inside_inner_message_loop_) { inside_inner_message_loop_) {
// We are in a message loop created by RenderAllMissingPagesNow. Quit from // We are in a message loop created by RenderAllMissingPagesNow. Quit from
// it. // it.
@ -361,8 +353,7 @@ void PrintViewManagerBase::DisconnectFromCurrentPrintJob() {
bool result = RenderAllMissingPagesNow(); bool result = RenderAllMissingPagesNow();
// Verify that assertion. // Verify that assertion.
if (print_job_.get() && if (print_job_.get() && print_job_->document() &&
print_job_->document() &&
!print_job_->document()->IsComplete()) { !print_job_->document()->IsComplete()) {
DCHECK(!result); DCHECK(!result);
// That failed. // That failed.

View file

@ -15,11 +15,9 @@ DEFINE_WEB_CONTENTS_USER_DATA_KEY(printing::PrintViewManagerBasic);
namespace printing { namespace printing {
PrintViewManagerBasic::PrintViewManagerBasic(content::WebContents* web_contents) PrintViewManagerBasic::PrintViewManagerBasic(content::WebContents* web_contents)
: PrintViewManagerBase(web_contents) { : PrintViewManagerBase(web_contents) {}
}
PrintViewManagerBasic::~PrintViewManagerBasic() { PrintViewManagerBasic::~PrintViewManagerBasic() {}
}
#if defined(OS_ANDROID) #if defined(OS_ANDROID)
void PrintViewManagerBasic::RenderProcessGone(base::TerminationStatus status) { void PrintViewManagerBasic::RenderProcessGone(base::TerminationStatus status) {

View file

@ -89,24 +89,24 @@ void PrinterQuery::GetSettings(GetSettingsAskParam ask_user_for_settings,
margin_type, is_scripted, is_modifiable, base::string16())); margin_type, is_scripted, is_modifiable, base::string16()));
} }
void PrinterQuery::GetSettings( void PrinterQuery::GetSettings(GetSettingsAskParam ask_user_for_settings,
GetSettingsAskParam ask_user_for_settings, int expected_page_count,
int expected_page_count, bool has_selection,
bool has_selection, MarginType margin_type,
MarginType margin_type, bool is_scripted,
bool is_scripted, bool is_modifiable,
bool is_modifiable, const base::string16& device_name,
const base::string16& device_name, const base::Closure& callback) {
const base::Closure& callback) {
DCHECK(RunsTasksInCurrentSequence()); DCHECK(RunsTasksInCurrentSequence());
DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_print_dialog_box_shown_);
StartWorker(callback); StartWorker(callback);
is_print_dialog_box_shown_ = false; is_print_dialog_box_shown_ = false;
worker_->PostTask(FROM_HERE, worker_->PostTask(
base::Bind(&PrintJobWorker::GetSettings, base::Unretained(worker_.get()), FROM_HERE,
is_print_dialog_box_shown_, expected_page_count, has_selection, base::Bind(&PrintJobWorker::GetSettings, base::Unretained(worker_.get()),
margin_type, is_scripted, is_modifiable, device_name)); is_print_dialog_box_shown_, expected_page_count, has_selection,
margin_type, is_scripted, is_modifiable, device_name));
} }
void PrinterQuery::SetSettings( void PrinterQuery::SetSettings(
@ -114,10 +114,9 @@ void PrinterQuery::SetSettings(
const base::Closure& callback) { const base::Closure& callback) {
StartWorker(callback); StartWorker(callback);
worker_->PostTask(FROM_HERE, worker_->PostTask(FROM_HERE, base::Bind(&PrintJobWorker::SetSettings,
base::Bind(&PrintJobWorker::SetSettings, base::Unretained(worker_.get()),
base::Unretained(worker_.get()), base::Passed(&new_settings)));
base::Passed(&new_settings)));
} }
void PrinterQuery::StartWorker(const base::Closure& callback) { void PrinterQuery::StartWorker(const base::Closure& callback) {

View file

@ -16,11 +16,9 @@
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/child_process_host.h" #include "content/public/common/child_process_host.h"
#include "printing/features/features.h" #include "printing/features/features.h"
#if defined(OS_ANDROID) #if defined(OS_ANDROID)
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
#include "chrome/browser/printing/print_view_manager_basic.h" #include "chrome/browser/printing/print_view_manager_basic.h"
@ -86,15 +84,15 @@ PrintingMessageFilter::PrintingMessageFilter(int render_process_id)
DCHECK(queue_.get()); DCHECK(queue_.get());
} }
PrintingMessageFilter::~PrintingMessageFilter() { PrintingMessageFilter::~PrintingMessageFilter() {}
}
void PrintingMessageFilter::OnDestruct() const { void PrintingMessageFilter::OnDestruct() const {
BrowserThread::DeleteOnUIThread::Destruct(this); BrowserThread::DeleteOnUIThread::Destruct(this);
} }
void PrintingMessageFilter::OverrideThreadForMessage( void PrintingMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) { const IPC::Message& message,
BrowserThread::ID* thread) {
#if defined(OS_ANDROID) #if defined(OS_ANDROID)
if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID || if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||
message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) { message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {
@ -174,8 +172,9 @@ void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
printer_query, reply_msg)); printer_query, reply_msg));
} }
void PrintingMessageFilter::OnInitSettingWithDeviceName(const base::string16& device_name, void PrintingMessageFilter::OnInitSettingWithDeviceName(
IPC::Message* reply_msg) { const base::string16& device_name,
IPC::Message* reply_msg) {
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);
scoped_refptr<PrinterQuery> printer_query; scoped_refptr<PrinterQuery> printer_query;
printer_query = queue_->PopPrinterQuery(0); printer_query = queue_->PopPrinterQuery(0);
@ -187,17 +186,10 @@ void PrintingMessageFilter::OnInitSettingWithDeviceName(const base::string16& de
// Loads default settings. This is asynchronous, only the IPC message sender // Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved. // will hang until the settings are retrieved.
printer_query->GetSettings( printer_query->GetSettings(
PrinterQuery::GetSettingsAskParam::DEFAULTS, PrinterQuery::GetSettingsAskParam::DEFAULTS, 0, false, DEFAULT_MARGINS,
0, true, true, device_name,
false, base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply, this,
DEFAULT_MARGINS, printer_query, reply_msg));
true,
true,
device_name,
base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
this,
printer_query,
reply_msg));
} }
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply( void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
@ -289,7 +281,8 @@ void PrintingMessageFilter::UpdateFileDescriptor(int render_view_id, int fd) {
#endif #endif
void PrintingMessageFilter::OnUpdatePrintSettings( void PrintingMessageFilter::OnUpdatePrintSettings(
int document_cookie, const base::DictionaryValue& job_settings, int document_cookie,
const base::DictionaryValue& job_settings,
IPC::Message* reply_msg) { IPC::Message* reply_msg) {
std::unique_ptr<base::DictionaryValue> new_settings(job_settings.DeepCopy()); std::unique_ptr<base::DictionaryValue> new_settings(job_settings.DeepCopy());

View file

@ -117,11 +117,12 @@ const int kMaxACKMessageLength = arraysize(kShutdownToken) - 1;
const char kLockDelimiter = '-'; const char kLockDelimiter = '-';
const base::FilePath::CharType kSingletonCookieFilename[] = const base::FilePath::CharType kSingletonCookieFilename[] =
FILE_PATH_LITERAL("SingletonCookie"); FILE_PATH_LITERAL("SingletonCookie");
const base::FilePath::CharType kSingletonLockFilename[] = FILE_PATH_LITERAL("SingletonLock"); const base::FilePath::CharType kSingletonLockFilename[] =
FILE_PATH_LITERAL("SingletonLock");
const base::FilePath::CharType kSingletonSocketFilename[] = const base::FilePath::CharType kSingletonSocketFilename[] =
FILE_PATH_LITERAL("SS"); FILE_PATH_LITERAL("SS");
// Set the close-on-exec bit on a file descriptor. // Set the close-on-exec bit on a file descriptor.
// Returns 0 on success, -1 on failure. // Returns 0 on success, -1 on failure.
@ -141,7 +142,7 @@ void CloseSocket(int fd) {
} }
// Write a message to a socket fd. // Write a message to a socket fd.
bool WriteToSocket(int fd, const char *message, size_t length) { bool WriteToSocket(int fd, const char* message, size_t length) {
DCHECK(message); DCHECK(message);
DCHECK(length); DCHECK(length);
size_t bytes_written = 0; size_t bytes_written = 0;
@ -343,6 +344,7 @@ class ScopedSocket {
CloseSocket(fd_); CloseSocket(fd_);
fd_ = -1; fd_ = -1;
} }
private: private:
int fd_; int fd_;
}; };
@ -380,8 +382,8 @@ bool ConnectSocket(ScopedSocket* socket,
base::FilePath cookie = ReadLink(cookie_path); base::FilePath cookie = ReadLink(cookie_path);
if (cookie.empty()) if (cookie.empty())
return false; return false;
base::FilePath remote_cookie = socket_target.DirName(). base::FilePath remote_cookie =
Append(kSingletonCookieFilename); socket_target.DirName().Append(kSingletonCookieFilename);
// Verify the cookie before connecting. // Verify the cookie before connecting.
if (!CheckCookie(remote_cookie, cookie)) if (!CheckCookie(remote_cookie, cookie))
return false; return false;
@ -389,9 +391,8 @@ bool ConnectSocket(ScopedSocket* socket,
// owner. Try to connect. // owner. Try to connect.
sockaddr_un addr; sockaddr_un addr;
SetupSockAddr(socket_target.value(), &addr); SetupSockAddr(socket_target.value(), &addr);
int ret = HANDLE_EINTR(connect(socket->fd(), int ret = HANDLE_EINTR(connect(
reinterpret_cast<sockaddr*>(&addr), socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)));
sizeof(addr)));
if (ret != 0) if (ret != 0)
return false; return false;
// Check the cookie again. We only link in /tmp, which is sticky, so, if the // Check the cookie again. We only link in /tmp, which is sticky, so, if the
@ -408,9 +409,8 @@ bool ConnectSocket(ScopedSocket* socket,
// later). Just connect to it directly; this is an older version of Chrome. // later). Just connect to it directly; this is an older version of Chrome.
sockaddr_un addr; sockaddr_un addr;
SetupSockAddr(socket_path.value(), &addr); SetupSockAddr(socket_path.value(), &addr);
int ret = HANDLE_EINTR(connect(socket->fd(), int ret = HANDLE_EINTR(connect(
reinterpret_cast<sockaddr*>(&addr), socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr)));
sizeof(addr)));
return (ret == 0); return (ret == 0);
} else { } else {
// File is missing, or other error. // File is missing, or other error.
@ -490,7 +490,7 @@ class ProcessSingleton::LinuxWatcher
// Finish handling the incoming message by optionally sending back an ACK // Finish handling the incoming message by optionally sending back an ACK
// message and removing this SocketReader. // message and removing this SocketReader.
void FinishWithACK(const char *message, size_t length); void FinishWithACK(const char* message, size_t length);
private: private:
void OnSocketCanReadWithoutBlocking(); void OnSocketCanReadWithoutBlocking();
@ -546,9 +546,7 @@ class ProcessSingleton::LinuxWatcher
friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>; friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>; friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>;
~LinuxWatcher() { ~LinuxWatcher() { DCHECK_CURRENTLY_ON(BrowserThread::IO); }
DCHECK_CURRENTLY_ON(BrowserThread::IO);
}
void OnSocketCanReadWithoutBlocking(int socket); void OnSocketCanReadWithoutBlocking(int socket);
@ -596,13 +594,13 @@ void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
} }
void ProcessSingleton::LinuxWatcher::HandleMessage( void ProcessSingleton::LinuxWatcher::HandleMessage(
const std::string& current_dir, const std::vector<std::string>& argv, const std::string& current_dir,
const std::vector<std::string>& argv,
SocketReader* reader) { SocketReader* reader) {
DCHECK(ui_task_runner_->BelongsToCurrentThread()); DCHECK(ui_task_runner_->BelongsToCurrentThread());
DCHECK(reader); DCHECK(reader);
if (parent_->notification_callback_.Run(argv, if (parent_->notification_callback_.Run(argv, base::FilePath(current_dir))) {
base::FilePath(current_dir))) {
// Send back "ACK" message to prevent the client process from starting up. // Send back "ACK" message to prevent the client process from starting up.
reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1); reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1);
} else { } else {
@ -663,9 +661,9 @@ void ProcessSingleton::LinuxWatcher::SocketReader::
} }
std::string str(buf_, bytes_read_); std::string str(buf_, bytes_read_);
std::vector<std::string> tokens = base::SplitString( std::vector<std::string> tokens =
str, std::string(1, kTokenDelimiter), base::SplitString(str, std::string(1, kTokenDelimiter),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (tokens.size() < 3 || tokens[0] != kStartToken) { if (tokens.size() < 3 || tokens[0] != kStartToken) {
LOG(ERROR) << "Wrong message format: " << str; LOG(ERROR) << "Wrong message format: " << str;
@ -694,7 +692,8 @@ void ProcessSingleton::LinuxWatcher::SocketReader::
} }
void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK( void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
const char *message, size_t length) { const char* message,
size_t length) {
if (message && length) { if (message && length) {
// Not necessary to care about the return value. // Not necessary to care about the return value.
WriteToSocket(fd_, message, length); WriteToSocket(fd_, message, length);
@ -704,10 +703,8 @@ void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK(
PLOG(ERROR) << "shutdown() failed"; PLOG(ERROR) << "shutdown() failed";
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, BrowserThread::IO, FROM_HERE,
FROM_HERE, base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader, parent_,
base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader,
parent_,
this)); this));
// We will be deleted once the posted RemoveSocketReader task runs. // We will be deleted once the posted RemoveSocketReader task runs.
} }
@ -728,8 +725,8 @@ ProcessSingleton::ProcessSingleton(
lock_path_ = user_data_dir.Append(kSingletonLockFilename); lock_path_ = user_data_dir.Append(kSingletonLockFilename);
cookie_path_ = user_data_dir.Append(kSingletonCookieFilename); cookie_path_ = user_data_dir.Append(kSingletonCookieFilename);
kill_callback_ = base::Bind(&ProcessSingleton::KillProcess, kill_callback_ =
base::Unretained(this)); base::Bind(&ProcessSingleton::KillProcess, base::Unretained(this));
} }
ProcessSingleton::~ProcessSingleton() { ProcessSingleton::~ProcessSingleton() {
@ -814,10 +811,7 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
} }
timeval socket_timeout = TimeDeltaToTimeVal(timeout); timeval socket_timeout = TimeDeltaToTimeVal(timeout);
setsockopt(socket.fd(), setsockopt(socket.fd(), SOL_SOCKET, SO_SNDTIMEO, &socket_timeout,
SOL_SOCKET,
SO_SNDTIMEO,
&socket_timeout,
sizeof(socket_timeout)); sizeof(socket_timeout));
// Found another process, prepare our command line // Found another process, prepare our command line
@ -832,7 +826,7 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout(
const std::vector<std::string>& argv = atom::AtomCommandLine::argv(); const std::vector<std::string>& argv = atom::AtomCommandLine::argv();
for (std::vector<std::string>::const_iterator it = argv.begin(); for (std::vector<std::string>::const_iterator it = argv.begin();
it != argv.end(); ++it) { it != argv.end(); ++it) {
to_send.push_back(kTokenDelimiter); to_send.push_back(kTokenDelimiter);
to_send.append(*it); to_send.append(*it);
} }
@ -889,10 +883,8 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
void ProcessSingleton::StartListeningOnSocket() { void ProcessSingleton::StartListeningOnSocket() {
watcher_ = new LinuxWatcher(this); watcher_ = new LinuxWatcher(this);
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, BrowserThread::IO, FROM_HERE,
FROM_HERE, base::Bind(&ProcessSingleton::LinuxWatcher::StartListening, watcher_,
base::Bind(&ProcessSingleton::LinuxWatcher::StartListening,
watcher_,
sock_)); sock_));
} }
@ -933,8 +925,8 @@ ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate(
// we did.) // we did.)
// This time, we don't want to kill anything if we aren't successful, since we // This time, we don't want to kill anything if we aren't successful, since we
// aren't going to try to take over the lock ourselves. // aren't going to try to take over the lock ourselves.
result = NotifyOtherProcessWithTimeout( result = NotifyOtherProcessWithTimeout(command_line, retry_attempts, timeout,
command_line, retry_attempts, timeout, false); false);
if (result == PROCESS_NOTIFIED) { if (result == PROCESS_NOTIFIED) {
UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify", UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify",
@ -971,10 +963,7 @@ bool ProcessSingleton::Create() {
// The symlink lock is pointed to the hostname and process id, so other // The symlink lock is pointed to the hostname and process id, so other
// processes can find it out. // processes can find it out.
base::FilePath symlink_content(base::StringPrintf( base::FilePath symlink_content(base::StringPrintf(
"%s%c%u", "%s%c%u", net::GetHostName().c_str(), kLockDelimiter, current_pid_));
net::GetHostName().c_str(),
kLockDelimiter,
current_pid_));
// Create symbol link before binding the socket, to ensure only one instance // Create symbol link before binding the socket, to ensure only one instance
// can have the socket open. // can have the socket open.
@ -1110,6 +1099,6 @@ void ProcessSingleton::KillProcess(int pid) {
int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL); int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL);
// ESRCH = No Such Process (can happen if the other process is already in // ESRCH = No Such Process (can happen if the other process is already in
// progress of shutting down and finishes before we try to kill it). // progress of shutting down and finishes before we try to kill it).
DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: " DCHECK(rv == 0 || errno == ESRCH)
<< base::safe_strerror(errno); << "Error killing process: " << base::safe_strerror(errno);
} }

View file

@ -110,8 +110,8 @@ bool ParseCommandLine(const COPYDATASTRUCT* cds,
const std::wstring::size_type first_null = msg.find_first_of(L'\0'); const std::wstring::size_type first_null = msg.find_first_of(L'\0');
if (first_null == 0 || first_null == std::wstring::npos) { if (first_null == 0 || first_null == std::wstring::npos) {
// no NULL byte, don't know what to do // no NULL byte, don't know what to do
LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length() << LOG(WARNING) << "Invalid WM_COPYDATA, length = " << msg.length()
", first null = " << first_null; << ", first null = " << first_null;
return false; return false;
} }
@ -122,23 +122,22 @@ bool ParseCommandLine(const COPYDATASTRUCT* cds,
VLOG(1) << "Handling STARTUP request from another process"; VLOG(1) << "Handling STARTUP request from another process";
const std::wstring::size_type second_null = const std::wstring::size_type second_null =
msg.find_first_of(L'\0', first_null + 1); msg.find_first_of(L'\0', first_null + 1);
if (second_null == std::wstring::npos || if (second_null == std::wstring::npos || first_null == msg.length() - 1 ||
first_null == msg.length() - 1 || second_null == msg.length()) { second_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 " LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs"; "parts separated by NULLs";
return false; return false;
} }
// Get current directory. // Get current directory.
*current_directory = base::FilePath(msg.substr(first_null + 1, *current_directory =
second_null - first_null)); base::FilePath(msg.substr(first_null + 1, second_null - first_null));
const std::wstring::size_type third_null = const std::wstring::size_type third_null =
msg.find_first_of(L'\0', second_null + 1); msg.find_first_of(L'\0', second_null + 1);
if (third_null == std::wstring::npos || if (third_null == std::wstring::npos || third_null == msg.length()) {
third_null == msg.length()) {
LOG(WARNING) << "Invalid format for start command, we need a string in 4 " LOG(WARNING) << "Invalid format for start command, we need a string in 4 "
"parts separated by NULLs"; "parts separated by NULLs";
} }
// Get command line. // Get command line.
@ -169,8 +168,9 @@ bool ProcessLaunchNotification(
return true; return true;
} }
*result = notification_callback.Run(parsed_command_line, current_directory) ? *result = notification_callback.Run(parsed_command_line, current_directory)
TRUE : FALSE; ? TRUE
: FALSE;
return true; return true;
} }
@ -231,8 +231,7 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
// The window is hung. Scan for every window to find a visible one. // The window is hung. Scan for every window to find a visible one.
bool visible_window = false; bool visible_window = false;
::EnumThreadWindows(thread_id, ::EnumThreadWindows(thread_id, &BrowserWindowEnumeration,
&BrowserWindowEnumeration,
reinterpret_cast<LPARAM>(&visible_window)); reinterpret_cast<LPARAM>(&visible_window));
// If there is a visible browser window, ask the user before killing it. // If there is a visible browser window, ask the user before killing it.
@ -247,8 +246,7 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() {
return PROCESS_NONE; return PROCESS_NONE;
} }
ProcessSingleton::NotifyResult ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() {
ProcessSingleton::NotifyOtherProcessOrCreate() {
ProcessSingleton::NotifyResult result = PROCESS_NONE; ProcessSingleton::NotifyResult result = PROCESS_NONE;
if (!Create()) { if (!Create()) {
result = NotifyOtherProcess(); result = NotifyOtherProcess();
@ -291,17 +289,14 @@ bool ProcessSingleton::Create() {
// We have to make sure there is no Chrome instance running on another // We have to make sure there is no Chrome instance running on another
// machine that uses the same profile. // machine that uses the same profile.
base::FilePath lock_file_path = user_data_dir_.AppendASCII(kLockfile); base::FilePath lock_file_path = user_data_dir_.AppendASCII(kLockfile);
lock_file_ = ::CreateFile(lock_file_path.value().c_str(), lock_file_ =
GENERIC_WRITE, ::CreateFile(lock_file_path.value().c_str(), GENERIC_WRITE,
FILE_SHARE_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS,
NULL, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_DELETE_ON_CLOSE,
NULL);
DWORD error = ::GetLastError(); DWORD error = ::GetLastError();
LOG_IF(WARNING, lock_file_ != INVALID_HANDLE_VALUE && LOG_IF(WARNING, lock_file_ != INVALID_HANDLE_VALUE &&
error == ERROR_ALREADY_EXISTS) << "Lock file exists but is writable."; error == ERROR_ALREADY_EXISTS)
<< "Lock file exists but is writable.";
LOG_IF(ERROR, lock_file_ == INVALID_HANDLE_VALUE) LOG_IF(ERROR, lock_file_ == INVALID_HANDLE_VALUE)
<< "Lock file can not be created! Error code: " << error; << "Lock file can not be created! Error code: " << error;
@ -315,7 +310,8 @@ bool ProcessSingleton::Create() {
// NB: Ensure that if the primary app gets started as elevated // NB: Ensure that if the primary app gets started as elevated
// admin inadvertently, secondary windows running not as elevated // admin inadvertently, secondary windows running not as elevated
// will still be able to send messages // will still be able to send messages
::ChangeWindowMessageFilterEx(window_.hwnd(), WM_COPYDATA, MSGFLT_ALLOW, NULL); ::ChangeWindowMessageFilterEx(window_.hwnd(), WM_COPYDATA, MSGFLT_ALLOW,
NULL);
CHECK(result && window_.hwnd()); CHECK(result && window_.hwnd());
} }
} }
@ -324,8 +320,7 @@ bool ProcessSingleton::Create() {
return window_.hwnd() != NULL; return window_.hwnd() != NULL;
} }
void ProcessSingleton::Cleanup() { void ProcessSingleton::Cleanup() {}
}
void ProcessSingleton::OverrideShouldKillRemoteProcessCallbackForTesting( void ProcessSingleton::OverrideShouldKillRemoteProcessCallbackForTesting(
const ShouldKillRemoteProcessCallback& display_dialog_callback) { const ShouldKillRemoteProcessCallback& display_dialog_callback) {

View file

@ -29,7 +29,8 @@ ChromeBrowserPepperHostFactory::ChromeBrowserPepperHostFactory(
ChromeBrowserPepperHostFactory::~ChromeBrowserPepperHostFactory() {} ChromeBrowserPepperHostFactory::~ChromeBrowserPepperHostFactory() {}
std::unique_ptr<ResourceHost> ChromeBrowserPepperHostFactory::CreateResourceHost( std::unique_ptr<ResourceHost>
ChromeBrowserPepperHostFactory::CreateResourceHost(
ppapi::host::PpapiHost* host, ppapi::host::PpapiHost* host,
PP_Resource resource, PP_Resource resource,
PP_Instance instance, PP_Instance instance,

View file

@ -92,8 +92,7 @@ int32_t PepperFlashBrowserHost::OnGetLocalDataRestrictions(
// call |GetLocalDataRestrictions| with it. // call |GetLocalDataRestrictions| with it.
GURL document_url = host_->GetDocumentURLForInstance(pp_instance()); GURL document_url = host_->GetDocumentURLForInstance(pp_instance());
GURL plugin_url = host_->GetPluginURLForInstance(pp_instance()); GURL plugin_url = host_->GetPluginURLForInstance(pp_instance());
GetLocalDataRestrictions(context->MakeReplyMessageContext(), GetLocalDataRestrictions(context->MakeReplyMessageContext(), document_url,
document_url,
plugin_url); plugin_url);
return PP_OK_COMPLETIONPENDING; return PP_OK_COMPLETIONPENDING;
} }
@ -105,9 +104,8 @@ void PepperFlashBrowserHost::GetLocalDataRestrictions(
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
PP_FlashLSORestrictions restrictions = PP_FLASHLSORESTRICTIONS_NONE; PP_FlashLSORestrictions restrictions = PP_FLASHLSORESTRICTIONS_NONE;
SendReply(reply_context, SendReply(reply_context, PpapiPluginMsg_Flash_GetLocalDataRestrictionsReply(
PpapiPluginMsg_Flash_GetLocalDataRestrictionsReply( static_cast<int32_t>(restrictions)));
static_cast<int32_t>(restrictions)));
} }
} // namespace chrome } // namespace chrome

View file

@ -87,8 +87,7 @@ void WriteDataToPickle(const std::map<base::string16, std::string>& data,
base::Pickle* pickle) { base::Pickle* pickle) {
pickle->WriteUInt32(data.size()); pickle->WriteUInt32(data.size());
for (std::map<base::string16, std::string>::const_iterator it = data.begin(); for (std::map<base::string16, std::string>::const_iterator it = data.begin();
it != data.end(); it != data.end(); ++it) {
++it) {
pickle->WriteString16(it->first); pickle->WriteString16(it->first);
pickle->WriteString(it->second); pickle->WriteString(it->second);
} }

View file

@ -66,7 +66,7 @@ bool GetSystemVolumeSerialNumber(std::string* number) {
} }
#endif #endif
} } // namespace
#if defined(OS_WIN) #if defined(OS_WIN)
// Helper class to get the UI thread which monitor is showing the // Helper class to get the UI thread which monitor is showing the
@ -89,8 +89,7 @@ class MonitorFinder : public base::RefCountedThreadSafe<MonitorFinder> {
// to call and we can't cache the |monitor_| value. // to call and we can't cache the |monitor_| value.
if (InterlockedCompareExchange(&request_sent_, 1, 0) == 0) { if (InterlockedCompareExchange(&request_sent_, 1, 0) == 0) {
content::BrowserThread::PostTask( content::BrowserThread::PostTask(
content::BrowserThread::UI, content::BrowserThread::UI, FROM_HERE,
FROM_HERE,
base::Bind(&MonitorFinder::FetchMonitorFromWidget, this)); base::Bind(&MonitorFinder::FetchMonitorFromWidget, this));
} }
return reinterpret_cast<int64_t>(monitor_); return reinterpret_cast<int64_t>(monitor_);

View file

@ -24,15 +24,13 @@ PepperIsolatedFileSystemMessageFilter::Create(PP_Instance instance,
content::BrowserPpapiHost* host) { content::BrowserPpapiHost* host) {
int render_process_id; int render_process_id;
int unused_render_frame_id; int unused_render_frame_id;
if (!host->GetRenderFrameIDsForInstance( if (!host->GetRenderFrameIDsForInstance(instance, &render_process_id,
instance, &render_process_id, &unused_render_frame_id)) { &unused_render_frame_id)) {
return NULL; return NULL;
} }
return new PepperIsolatedFileSystemMessageFilter( return new PepperIsolatedFileSystemMessageFilter(
render_process_id, render_process_id, host->GetProfileDataDirectory(),
host->GetProfileDataDirectory(), host->GetDocumentURLForInstance(instance), host->GetPpapiHost());
host->GetDocumentURLForInstance(instance),
host->GetPpapiHost());
} }
PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter( PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter(
@ -43,8 +41,7 @@ PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter(
: render_process_id_(render_process_id), : render_process_id_(render_process_id),
profile_directory_(profile_directory), profile_directory_(profile_directory),
document_url_(document_url), document_url_(document_url),
ppapi_host_(ppapi_host) { ppapi_host_(ppapi_host) {}
}
PepperIsolatedFileSystemMessageFilter:: PepperIsolatedFileSystemMessageFilter::
~PepperIsolatedFileSystemMessageFilter() {} ~PepperIsolatedFileSystemMessageFilter() {}
@ -63,8 +60,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived(
ppapi::host::HostMessageContext* context) { ppapi::host::HostMessageContext* context) {
PPAPI_BEGIN_MESSAGE_MAP(PepperIsolatedFileSystemMessageFilter, msg) PPAPI_BEGIN_MESSAGE_MAP(PepperIsolatedFileSystemMessageFilter, msg)
PPAPI_DISPATCH_HOST_RESOURCE_CALL( PPAPI_DISPATCH_HOST_RESOURCE_CALL(
PpapiHostMsg_IsolatedFileSystem_BrowserOpen, PpapiHostMsg_IsolatedFileSystem_BrowserOpen, OnOpenFileSystem)
OnOpenFileSystem)
PPAPI_END_MESSAGE_MAP() PPAPI_END_MESSAGE_MAP()
return PP_ERROR_FAILED; return PP_ERROR_FAILED;
} }

View file

@ -6,29 +6,27 @@
#include "base/bind.h" #include "base/bind.h"
#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_context.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h" #include "content/public/browser/render_process_host.h"
#include "content/public/common/webplugininfo.h" #include "content/public/common/webplugininfo.h"
#include "content/public/browser/plugin_service.h"
#include "media/media_features.h" #include "media/media_features.h"
using content::BrowserThread;
using content::PluginService; using content::PluginService;
using content::WebPluginInfo; using content::WebPluginInfo;
using content::BrowserThread;
WidevineCdmMessageFilter::WidevineCdmMessageFilter( WidevineCdmMessageFilter::WidevineCdmMessageFilter(
int render_process_id, int render_process_id,
content::BrowserContext* browser_context) content::BrowserContext* browser_context)
: BrowserMessageFilter(ChromeMsgStart), : BrowserMessageFilter(ChromeMsgStart),
render_process_id_(render_process_id), render_process_id_(render_process_id),
browser_context_(browser_context) { browser_context_(browser_context) {}
}
bool WidevineCdmMessageFilter::OnMessageReceived(const IPC::Message& message) { bool WidevineCdmMessageFilter::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(WidevineCdmMessageFilter, message) IPC_BEGIN_MESSAGE_MAP(WidevineCdmMessageFilter, message)
#if BUILDFLAG(ENABLE_LIBRARY_CDMS) #if BUILDFLAG(ENABLE_LIBRARY_CDMS)
IPC_MESSAGE_HANDLER( IPC_MESSAGE_HANDLER(ChromeViewHostMsg_IsInternalPluginAvailableForMimeType,
ChromeViewHostMsg_IsInternalPluginAvailableForMimeType, OnIsInternalPluginAvailableForMimeType)
OnIsInternalPluginAvailableForMimeType)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS) #endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)
IPC_MESSAGE_UNHANDLED(return false) IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP() IPC_END_MESSAGE_MAP()
@ -49,7 +47,6 @@ void WidevineCdmMessageFilter::OnIsInternalPluginAvailableForMimeType(
const std::vector<content::WebPluginMimeType>& mime_types = const std::vector<content::WebPluginMimeType>& mime_types =
plugin.mime_types; plugin.mime_types;
for (size_t j = 0; j < mime_types.size(); ++j) { for (size_t j = 0; j < mime_types.size(); ++j) {
if (mime_types[j].mime_type == mime_type) { if (mime_types[j].mime_type == mime_type) {
*is_available = true; *is_available = true;
*additional_param_names = mime_types[j].additional_param_names; *additional_param_names = mime_types[j].additional_param_names;
@ -67,5 +64,4 @@ void WidevineCdmMessageFilter::OnDestruct() const {
BrowserThread::DeleteOnUIThread::Destruct(this); BrowserThread::DeleteOnUIThread::Destruct(this);
} }
WidevineCdmMessageFilter::~WidevineCdmMessageFilter() { WidevineCdmMessageFilter::~WidevineCdmMessageFilter() {}
}

View file

@ -27,36 +27,26 @@ std::string TrimLanguageCode(std::string lang) {
} // namespace } // namespace
bool IsFinalTtsEventType(TtsEventType event_type) { bool IsFinalTtsEventType(TtsEventType event_type) {
return (event_type == TTS_EVENT_END || return (event_type == TTS_EVENT_END || event_type == TTS_EVENT_INTERRUPTED ||
event_type == TTS_EVENT_INTERRUPTED || event_type == TTS_EVENT_CANCELLED || event_type == TTS_EVENT_ERROR);
event_type == TTS_EVENT_CANCELLED ||
event_type == TTS_EVENT_ERROR);
} }
// //
// UtteranceContinuousParameters // UtteranceContinuousParameters
// //
UtteranceContinuousParameters::UtteranceContinuousParameters() UtteranceContinuousParameters::UtteranceContinuousParameters()
: rate(-1), : rate(-1), pitch(-1), volume(-1) {}
pitch(-1),
volume(-1) {}
// //
// VoiceData // VoiceData
// //
VoiceData::VoiceData() VoiceData::VoiceData()
: gender(TTS_GENDER_NONE), : gender(TTS_GENDER_NONE), remote(false), native(false) {}
remote(false),
native(false) {}
VoiceData::~VoiceData() {} VoiceData::~VoiceData() {}
// //
// Utterance // Utterance
// //
@ -118,8 +108,7 @@ TtsControllerImpl::TtsControllerImpl()
: current_utterance_(NULL), : current_utterance_(NULL),
paused_(false), paused_(false),
platform_impl_(NULL), platform_impl_(NULL),
tts_engine_delegate_(NULL) { tts_engine_delegate_(NULL) {}
}
TtsControllerImpl::~TtsControllerImpl() { TtsControllerImpl::~TtsControllerImpl() {
if (current_utterance_) { if (current_utterance_) {
@ -215,12 +204,9 @@ void TtsControllerImpl::SpeakNow(Utterance* utterance) {
// during |speak|. // during |speak|.
current_utterance_ = utterance; current_utterance_ = utterance;
GetPlatformImpl()->clear_error(); GetPlatformImpl()->clear_error();
bool success = GetPlatformImpl()->Speak( bool success = GetPlatformImpl()->Speak(utterance->id(), utterance->text(),
utterance->id(), utterance->lang(), voice,
utterance->text(), utterance->continuous_parameters());
utterance->lang(),
voice,
utterance->continuous_parameters());
if (!success) if (!success)
current_utterance_ = NULL; current_utterance_ = NULL;
@ -288,9 +274,9 @@ void TtsControllerImpl::Resume() {
} }
void TtsControllerImpl::OnTtsEvent(int utterance_id, void TtsControllerImpl::OnTtsEvent(int utterance_id,
TtsEventType event_type, TtsEventType event_type,
int char_index, int char_index,
const std::string& error_message) { const std::string& error_message) {
// We may sometimes receive completion callbacks "late", after we've // We may sometimes receive completion callbacks "late", after we've
// already finished the utterance (for example because another utterance // already finished the utterance (for example because another utterance
// interrupted or we got a call to Stop). This is normal and we can // interrupted or we got a call to Stop). This is normal and we can
@ -306,7 +292,7 @@ void TtsControllerImpl::OnTtsEvent(int utterance_id,
} }
void TtsControllerImpl::GetVoices(content::BrowserContext* browser_context, void TtsControllerImpl::GetVoices(content::BrowserContext* browser_context,
std::vector<VoiceData>* out_voices) { std::vector<VoiceData>* out_voices) {
#if !defined(OS_ANDROID) #if !defined(OS_ANDROID)
if (browser_context && tts_engine_delegate_) if (browser_context && tts_engine_delegate_)
tts_engine_delegate_->GetVoices(browser_context, out_voices); tts_engine_delegate_->GetVoices(browser_context, out_voices);
@ -362,8 +348,7 @@ void TtsControllerImpl::ClearUtteranceQueue(bool send_events) {
} }
} }
void TtsControllerImpl::SetPlatformImpl( void TtsControllerImpl::SetPlatformImpl(TtsPlatformImpl* platform_impl) {
TtsPlatformImpl* platform_impl) {
platform_impl_ = platform_impl; platform_impl_ = platform_impl;
} }
@ -377,8 +362,8 @@ TtsPlatformImpl* TtsControllerImpl::GetPlatformImpl() {
return platform_impl_; return platform_impl_;
} }
int TtsControllerImpl::GetMatchingVoice( int TtsControllerImpl::GetMatchingVoice(const Utterance* utterance,
const Utterance* utterance, std::vector<VoiceData>& voices) { std::vector<VoiceData>& voices) {
// Make two passes: the first time, do strict language matching // Make two passes: the first time, do strict language matching
// ('fr-FR' does not match 'fr-CA'). The second time, do prefix // ('fr-FR' does not match 'fr-CA'). The second time, do prefix
// language matching ('fr-FR' matches 'fr' and 'fr-CA') // language matching ('fr-FR' matches 'fr' and 'fr-CA')
@ -391,8 +376,7 @@ int TtsControllerImpl::GetMatchingVoice(
continue; continue;
} }
if (!voice.name.empty() && if (!voice.name.empty() && !utterance->voice_name().empty() &&
!utterance->voice_name().empty() &&
voice.name != utterance->voice_name()) { voice.name != utterance->voice_name()) {
continue; continue;
} }
@ -417,8 +401,7 @@ int TtsControllerImpl::GetMatchingVoice(
bool has_all_required_event_types = true; bool has_all_required_event_types = true;
for (std::set<TtsEventType>::const_iterator iter = for (std::set<TtsEventType>::const_iterator iter =
utterance->required_event_types().begin(); utterance->required_event_types().begin();
iter != utterance->required_event_types().end(); iter != utterance->required_event_types().end(); ++iter) {
++iter) {
if (voice.events.find(*iter) == voice.events.end()) { if (voice.events.find(*iter) == voice.events.end()) {
has_all_required_event_types = false; has_all_required_event_types = false;
break; break;
@ -453,8 +436,7 @@ void TtsControllerImpl::RemoveVoicesChangedDelegate(
voices_changed_delegates_.erase(delegate); voices_changed_delegates_.erase(delegate);
} }
void TtsControllerImpl::SetTtsEngineDelegate( void TtsControllerImpl::SetTtsEngineDelegate(TtsEngineDelegate* delegate) {
TtsEngineDelegate* delegate) {
tts_engine_delegate_ = delegate; tts_engine_delegate_ = delegate;
} }

View file

@ -81,7 +81,7 @@ class TtsPlatformImplLinux : public TtsPlatformImpl {
// Map a string composed of a voicename and module to the voicename. Used to // Map a string composed of a voicename and module to the voicename. Used to
// uniquely identify a voice across all available modules. // uniquely identify a voice across all available modules.
std::unique_ptr<std::map<std::string, SPDChromeVoice> > all_native_voices_; std::unique_ptr<std::map<std::string, SPDChromeVoice>> all_native_voices_;
friend struct base::DefaultSingletonTraits<TtsPlatformImplLinux>; friend struct base::DefaultSingletonTraits<TtsPlatformImplLinux>;
@ -89,20 +89,17 @@ class TtsPlatformImplLinux : public TtsPlatformImpl {
}; };
// static // static
SPDNotificationType TtsPlatformImplLinux::current_notification_ = SPDNotificationType TtsPlatformImplLinux::current_notification_ = SPD_EVENT_END;
SPD_EVENT_END;
TtsPlatformImplLinux::TtsPlatformImplLinux() TtsPlatformImplLinux::TtsPlatformImplLinux() : utterance_id_(0) {
: utterance_id_(0) {
const base::CommandLine& command_line = const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess(); *base::CommandLine::ForCurrentProcess();
if (!command_line.HasSwitch(switches::kEnableSpeechDispatcher)) if (!command_line.HasSwitch(switches::kEnableSpeechDispatcher))
return; return;
BrowserThread::PostTask(BrowserThread::FILE, BrowserThread::PostTask(
FROM_HERE, BrowserThread::FILE, FROM_HERE,
base::Bind(&TtsPlatformImplLinux::Initialize, base::Bind(&TtsPlatformImplLinux::Initialize, base::Unretained(this)));
base::Unretained(this)));
} }
void TtsPlatformImplLinux::Initialize() { void TtsPlatformImplLinux::Initialize() {
@ -115,19 +112,15 @@ void TtsPlatformImplLinux::Initialize() {
// spd_open has memory leaks which are hard to suppress. // spd_open has memory leaks which are hard to suppress.
// http://crbug.com/317360 // http://crbug.com/317360
ANNOTATE_SCOPED_MEMORY_LEAK; ANNOTATE_SCOPED_MEMORY_LEAK;
conn_ = libspeechd_loader_.spd_open( conn_ = libspeechd_loader_.spd_open("chrome", "extension_api", NULL,
"chrome", "extension_api", NULL, SPD_MODE_THREADED); SPD_MODE_THREADED);
} }
if (!conn_) if (!conn_)
return; return;
// Register callbacks for all events. // Register callbacks for all events.
conn_->callback_begin = conn_->callback_begin = conn_->callback_end = conn_->callback_cancel =
conn_->callback_end = conn_->callback_pause = conn_->callback_resume = &NotificationCallback;
conn_->callback_cancel =
conn_->callback_pause =
conn_->callback_resume =
&NotificationCallback;
conn_->callback_im = &IndexMarkCallback; conn_->callback_im = &IndexMarkCallback;
@ -150,8 +143,8 @@ void TtsPlatformImplLinux::Reset() {
base::AutoLock lock(initialization_lock_); base::AutoLock lock(initialization_lock_);
if (conn_) if (conn_)
libspeechd_loader_.spd_close(conn_); libspeechd_loader_.spd_close(conn_);
conn_ = libspeechd_loader_.spd_open( conn_ = libspeechd_loader_.spd_open("chrome", "extension_api", NULL,
"chrome", "extension_api", NULL, SPD_MODE_THREADED); SPD_MODE_THREADED);
} }
bool TtsPlatformImplLinux::PlatformImplAvailable() { bool TtsPlatformImplLinux::PlatformImplAvailable() {
@ -162,12 +155,11 @@ bool TtsPlatformImplLinux::PlatformImplAvailable() {
return result; return result;
} }
bool TtsPlatformImplLinux::Speak( bool TtsPlatformImplLinux::Speak(int utterance_id,
int utterance_id, const std::string& utterance,
const std::string& utterance, const std::string& lang,
const std::string& lang, const VoiceData& voice,
const VoiceData& voice, const UtteranceContinuousParameters& params) {
const UtteranceContinuousParameters& params) {
if (!PlatformImplAvailable()) { if (!PlatformImplAvailable()) {
error_ = kNotSupportedError; error_ = kNotSupportedError;
return false; return false;
@ -232,8 +224,7 @@ bool TtsPlatformImplLinux::IsSpeaking() {
return current_notification_ == SPD_EVENT_BEGIN; return current_notification_ == SPD_EVENT_BEGIN;
} }
void TtsPlatformImplLinux::GetVoices( void TtsPlatformImplLinux::GetVoices(std::vector<VoiceData>* out_voices) {
std::vector<VoiceData>* out_voices) {
if (!all_native_voices_.get()) { if (!all_native_voices_.get()) {
all_native_voices_.reset(new std::map<std::string, SPDChromeVoice>()); all_native_voices_.reset(new std::map<std::string, SPDChromeVoice>());
char** modules = libspeechd_loader_.spd_list_modules(conn_); char** modules = libspeechd_loader_.spd_list_modules(conn_);
@ -267,8 +258,7 @@ void TtsPlatformImplLinux::GetVoices(
for (std::map<std::string, SPDChromeVoice>::iterator it = for (std::map<std::string, SPDChromeVoice>::iterator it =
all_native_voices_->begin(); all_native_voices_->begin();
it != all_native_voices_->end(); it != all_native_voices_->end(); it++) {
it++) {
out_voices->push_back(VoiceData()); out_voices->push_back(VoiceData());
VoiceData& voice = out_voices->back(); VoiceData& voice = out_voices->back();
voice.native = true; voice.native = true;
@ -285,40 +275,40 @@ void TtsPlatformImplLinux::GetVoices(
void TtsPlatformImplLinux::OnSpeechEvent(SPDNotificationType type) { void TtsPlatformImplLinux::OnSpeechEvent(SPDNotificationType type) {
TtsController* controller = TtsController::GetInstance(); TtsController* controller = TtsController::GetInstance();
switch (type) { switch (type) {
case SPD_EVENT_BEGIN: case SPD_EVENT_BEGIN:
controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0, std::string()); controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0, std::string());
break; break;
case SPD_EVENT_RESUME: case SPD_EVENT_RESUME:
controller->OnTtsEvent(utterance_id_, TTS_EVENT_RESUME, 0, std::string()); controller->OnTtsEvent(utterance_id_, TTS_EVENT_RESUME, 0, std::string());
break; break;
case SPD_EVENT_END: case SPD_EVENT_END:
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_END, utterance_.size(),
utterance_id_, TTS_EVENT_END, utterance_.size(), std::string()); std::string());
break; break;
case SPD_EVENT_PAUSE: case SPD_EVENT_PAUSE:
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_PAUSE, utterance_.size(),
utterance_id_, TTS_EVENT_PAUSE, utterance_.size(), std::string()); std::string());
break; break;
case SPD_EVENT_CANCEL: case SPD_EVENT_CANCEL:
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_CANCELLED, 0,
utterance_id_, TTS_EVENT_CANCELLED, 0, std::string()); std::string());
break; break;
case SPD_EVENT_INDEX_MARK: case SPD_EVENT_INDEX_MARK:
controller->OnTtsEvent(utterance_id_, TTS_EVENT_MARKER, 0, std::string()); controller->OnTtsEvent(utterance_id_, TTS_EVENT_MARKER, 0, std::string());
break; break;
} }
} }
// static // static
void TtsPlatformImplLinux::NotificationCallback( void TtsPlatformImplLinux::NotificationCallback(size_t msg_id,
size_t msg_id, size_t client_id, SPDNotificationType type) { size_t client_id,
SPDNotificationType type) {
// We run Speech Dispatcher in threaded mode, so these callbacks should always // We run Speech Dispatcher in threaded mode, so these callbacks should always
// be in a separate thread. // be in a separate thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
current_notification_ = type; current_notification_ = type;
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, BrowserThread::UI, FROM_HERE,
FROM_HERE,
base::Bind(&TtsPlatformImplLinux::OnSpeechEvent, base::Bind(&TtsPlatformImplLinux::OnSpeechEvent,
base::Unretained(TtsPlatformImplLinux::GetInstance()), base::Unretained(TtsPlatformImplLinux::GetInstance()),
type)); type));
@ -327,9 +317,9 @@ void TtsPlatformImplLinux::NotificationCallback(
// static // static
void TtsPlatformImplLinux::IndexMarkCallback(size_t msg_id, void TtsPlatformImplLinux::IndexMarkCallback(size_t msg_id,
size_t client_id, size_t client_id,
SPDNotificationType state, SPDNotificationType state,
char* index_mark) { char* index_mark) {
// TODO(dtseng): index_mark appears to specify an index type supplied by a // TODO(dtseng): index_mark appears to specify an index type supplied by a
// client. Need to explore how this is used before hooking it up with existing // client. Need to explore how this is used before hooking it up with existing
// word, sentence events. // word, sentence events.
@ -337,10 +327,11 @@ void TtsPlatformImplLinux::IndexMarkCallback(size_t msg_id,
// be in a separate thread. // be in a separate thread.
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
current_notification_ = state; current_notification_ = state;
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&TtsPlatformImplLinux::OnSpeechEvent, base::Bind(&TtsPlatformImplLinux::OnSpeechEvent,
base::Unretained(TtsPlatformImplLinux::GetInstance()), base::Unretained(TtsPlatformImplLinux::GetInstance()),
state)); state));
} }
} }

View file

@ -25,16 +25,16 @@ TtsMessageFilter::TtsMessageFilter(int render_process_id,
AddRef(); AddRef();
} }
void TtsMessageFilter::OverrideThreadForMessage( void TtsMessageFilter::OverrideThreadForMessage(const IPC::Message& message,
const IPC::Message& message, BrowserThread::ID* thread) { BrowserThread::ID* thread) {
switch (message.type()) { switch (message.type()) {
case TtsHostMsg_InitializeVoiceList::ID: case TtsHostMsg_InitializeVoiceList::ID:
case TtsHostMsg_Speak::ID: case TtsHostMsg_Speak::ID:
case TtsHostMsg_Pause::ID: case TtsHostMsg_Pause::ID:
case TtsHostMsg_Resume::ID: case TtsHostMsg_Resume::ID:
case TtsHostMsg_Cancel::ID: case TtsHostMsg_Cancel::ID:
*thread = BrowserThread::UI; *thread = BrowserThread::UI;
break; break;
} }
} }
@ -144,8 +144,8 @@ void TtsMessageFilter::OnTtsEvent(Utterance* utterance,
Send(new TtsMsg_WasCancelled(utterance->src_id())); Send(new TtsMsg_WasCancelled(utterance->src_id()));
break; break;
case TTS_EVENT_ERROR: case TTS_EVENT_ERROR:
Send(new TtsMsg_SpeakingErrorOccurred( Send(
utterance->src_id(), error_message)); new TtsMsg_SpeakingErrorOccurred(utterance->src_id(), error_message));
break; break;
case TTS_EVENT_PAUSE: case TTS_EVENT_PAUSE:
Send(new TtsMsg_DidPauseSpeaking(utterance->src_id())); Send(new TtsMsg_DidPauseSpeaking(utterance->src_id()));

View file

@ -16,16 +16,13 @@
class TtsPlatformImplWin : public TtsPlatformImpl { class TtsPlatformImplWin : public TtsPlatformImpl {
public: public:
bool PlatformImplAvailable() override { bool PlatformImplAvailable() override { return true; }
return true;
}
bool Speak( bool Speak(int utterance_id,
int utterance_id, const std::string& utterance,
const std::string& utterance, const std::string& lang,
const std::string& lang, const VoiceData& voice,
const VoiceData& voice, const UtteranceContinuousParameters& params) override;
const UtteranceContinuousParameters& params) override;
bool StopSpeaking() override; bool StopSpeaking() override;
@ -68,12 +65,11 @@ TtsPlatformImpl* TtsPlatformImpl::GetInstance() {
return TtsPlatformImplWin::GetInstance(); return TtsPlatformImplWin::GetInstance();
} }
bool TtsPlatformImplWin::Speak( bool TtsPlatformImplWin::Speak(int utterance_id,
int utterance_id, const std::string& src_utterance,
const std::string& src_utterance, const std::string& lang,
const std::string& lang, const VoiceData& voice,
const VoiceData& voice, const UtteranceContinuousParameters& params) {
const UtteranceContinuousParameters& params) {
std::wstring prefix; std::wstring prefix;
std::wstring suffix; std::wstring suffix;
@ -114,10 +110,8 @@ bool TtsPlatformImplWin::Speak(
std::wstring merged_utterance = prefix + utterance_ + suffix; std::wstring merged_utterance = prefix + utterance_ + suffix;
prefix_len_ = prefix.size(); prefix_len_ = prefix.size();
HRESULT result = speech_synthesizer_->Speak( HRESULT result = speech_synthesizer_->Speak(merged_utterance.c_str(),
merged_utterance.c_str(), SPF_ASYNC, &stream_number_);
SPF_ASYNC,
&stream_number_);
return (result == S_OK); return (result == S_OK);
} }
@ -143,8 +137,8 @@ void TtsPlatformImplWin::Pause() {
if (speech_synthesizer_.Get() && utterance_id_ && !paused_) { if (speech_synthesizer_.Get() && utterance_id_ && !paused_) {
speech_synthesizer_->Pause(); speech_synthesizer_->Pause();
paused_ = true; paused_ = true;
TtsController::GetInstance()->OnTtsEvent( TtsController::GetInstance()->OnTtsEvent(utterance_id_, TTS_EVENT_PAUSE,
utterance_id_, TTS_EVENT_PAUSE, char_position_, ""); char_position_, "");
} }
} }
@ -152,8 +146,8 @@ void TtsPlatformImplWin::Resume() {
if (speech_synthesizer_.Get() && utterance_id_ && paused_) { if (speech_synthesizer_.Get() && utterance_id_ && paused_) {
speech_synthesizer_->Resume(); speech_synthesizer_->Resume();
paused_ = false; paused_ = false;
TtsController::GetInstance()->OnTtsEvent( TtsController::GetInstance()->OnTtsEvent(utterance_id_, TTS_EVENT_RESUME,
utterance_id_, TTS_EVENT_RESUME, char_position_, ""); char_position_, "");
} }
} }
@ -171,8 +165,7 @@ bool TtsPlatformImplWin::IsSpeaking() {
return false; return false;
} }
void TtsPlatformImplWin::GetVoices( void TtsPlatformImplWin::GetVoices(std::vector<VoiceData>* out_voices) {
std::vector<VoiceData>* out_voices) {
// TODO: get all voices, not just default voice. // TODO: get all voices, not just default voice.
// http://crbug.com/88059 // http://crbug.com/88059
out_voices->push_back(VoiceData()); out_voices->push_back(VoiceData());
@ -196,51 +189,47 @@ void TtsPlatformImplWin::OnSpeechEvent() {
continue; continue;
switch (event.eEventId) { switch (event.eEventId) {
case SPEI_START_INPUT_STREAM: case SPEI_START_INPUT_STREAM:
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0,
utterance_id_, TTS_EVENT_START, 0, std::string()); std::string());
break; break;
case SPEI_END_INPUT_STREAM: case SPEI_END_INPUT_STREAM:
char_position_ = utterance_.size(); char_position_ = utterance_.size();
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_END, char_position_,
utterance_id_, TTS_EVENT_END, char_position_, std::string()); std::string());
break; break;
case SPEI_TTS_BOOKMARK: case SPEI_TTS_BOOKMARK:
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_MARKER, char_position_,
utterance_id_, TTS_EVENT_MARKER, char_position_, std::string()); std::string());
break; break;
case SPEI_WORD_BOUNDARY: case SPEI_WORD_BOUNDARY:
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_; char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
controller->OnTtsEvent( controller->OnTtsEvent(utterance_id_, TTS_EVENT_WORD, char_position_,
utterance_id_, TTS_EVENT_WORD, char_position_, std::string());
std::string()); break;
break; case SPEI_SENTENCE_BOUNDARY:
case SPEI_SENTENCE_BOUNDARY: char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_;
char_position_ = static_cast<ULONG>(event.lParam) - prefix_len_; controller->OnTtsEvent(utterance_id_, TTS_EVENT_SENTENCE,
controller->OnTtsEvent( char_position_, std::string());
utterance_id_, TTS_EVENT_SENTENCE, char_position_, break;
std::string()); default:
break; break;
default:
break;
} }
} }
} }
TtsPlatformImplWin::TtsPlatformImplWin() TtsPlatformImplWin::TtsPlatformImplWin()
: utterance_id_(0), : utterance_id_(0),
prefix_len_(0), prefix_len_(0),
stream_number_(0), stream_number_(0),
char_position_(0), char_position_(0),
paused_(false) { paused_(false) {
::CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, ::CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL,
IID_PPV_ARGS(&speech_synthesizer_)); IID_PPV_ARGS(&speech_synthesizer_));
if (speech_synthesizer_.Get()) { if (speech_synthesizer_.Get()) {
ULONGLONG event_mask = ULONGLONG event_mask =
SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_TTS_BOOKMARK) |
SPFEI(SPEI_TTS_BOOKMARK) | SPFEI(SPEI_WORD_BOUNDARY) | SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_WORD_BOUNDARY) |
SPFEI(SPEI_SENTENCE_BOUNDARY) |
SPFEI(SPEI_END_INPUT_STREAM); SPFEI(SPEI_END_INPUT_STREAM);
speech_synthesizer_->SetInterest(event_mask, event_mask); speech_synthesizer_->SetInterest(event_mask, event_mask);
speech_synthesizer_->SetNotifyCallbackFunction( speech_synthesizer_->SetNotifyCallbackFunction(
@ -255,7 +244,6 @@ TtsPlatformImplWin* TtsPlatformImplWin::GetInstance() {
} }
// static // static
void TtsPlatformImplWin::SpeechEventCallback( void TtsPlatformImplWin::SpeechEventCallback(WPARAM w_param, LPARAM l_param) {
WPARAM w_param, LPARAM l_param) {
GetInstance()->OnSpeechEvent(); GetInstance()->OnSpeechEvent();
} }

View file

@ -128,7 +128,7 @@ void SecurityStateTabHelper::DidStartNavigation(
void SecurityStateTabHelper::DidFinishNavigation( void SecurityStateTabHelper::DidFinishNavigation(
content::NavigationHandle* navigation_handle) { content::NavigationHandle* navigation_handle) {
if (navigation_handle->IsInMainFrame() && if (navigation_handle->IsInMainFrame() &&
!navigation_handle->IsSameDocument()) { !navigation_handle->IsSameDocument()) {
// Only reset the console message flag for main-frame navigations, // Only reset the console message flag for main-frame navigations,
// and not for same-page navigations like reference fragments and pushState. // and not for same-page navigations like reference fragments and pushState.
logged_http_warning_on_current_navigation_ = false; logged_http_warning_on_current_navigation_ = false;

View file

@ -52,8 +52,8 @@ void ColorChooserAura::SetSelectedColor(SkColor color) {
} }
// static // static
ColorChooserAura* ColorChooserAura::Open( ColorChooserAura* ColorChooserAura::Open(content::WebContents* web_contents,
content::WebContents* web_contents, SkColor initial_color) { SkColor initial_color) {
return new ColorChooserAura(web_contents, initial_color); return new ColorChooserAura(web_contents, initial_color);
} }

View file

@ -22,10 +22,7 @@ COLORREF ColorChooserDialog::g_custom_colors[16];
ColorChooserDialog::ExecuteOpenParams::ExecuteOpenParams(SkColor color, ColorChooserDialog::ExecuteOpenParams::ExecuteOpenParams(SkColor color,
RunState run_state, RunState run_state,
HWND owner) HWND owner)
: color(color), : color(color), run_state(run_state), owner(owner) {}
run_state(run_state),
owner(owner) {
}
ColorChooserDialog::ColorChooserDialog(views::ColorChooserListener* listener, ColorChooserDialog::ColorChooserDialog(views::ColorChooserListener* listener,
SkColor initial_color, SkColor initial_color,
@ -36,16 +33,16 @@ ColorChooserDialog::ColorChooserDialog(views::ColorChooserListener* listener,
HWND owning_hwnd = views::HWNDForNativeWindow(owning_window); HWND owning_hwnd = views::HWNDForNativeWindow(owning_window);
ExecuteOpenParams execute_params(initial_color, BeginRun(owning_hwnd), ExecuteOpenParams execute_params(initial_color, BeginRun(owning_hwnd),
owning_hwnd); owning_hwnd);
execute_params.run_state.dialog_thread->task_runner()->PostTask(FROM_HERE, execute_params.run_state.dialog_thread->task_runner()->PostTask(
FROM_HERE,
base::Bind(&ColorChooserDialog::ExecuteOpen, this, execute_params)); base::Bind(&ColorChooserDialog::ExecuteOpen, this, execute_params));
} }
ColorChooserDialog::~ColorChooserDialog() { ColorChooserDialog::~ColorChooserDialog() {}
}
bool ColorChooserDialog::IsRunning(gfx::NativeWindow owning_window) const { bool ColorChooserDialog::IsRunning(gfx::NativeWindow owning_window) const {
return listener_ && IsRunningDialogForOwner( return listener_ &&
views::HWNDForNativeWindow(owning_window)); IsRunningDialogForOwner(views::HWNDForNativeWindow(owning_window));
} }
void ColorChooserDialog::ListenerDestroyed() { void ColorChooserDialog::ListenerDestroyed() {
@ -63,7 +60,8 @@ void ColorChooserDialog::ExecuteOpen(const ExecuteOpenParams& params) {
cc.Flags = CC_ANYCOLOR | CC_FULLOPEN | CC_RGBINIT; cc.Flags = CC_ANYCOLOR | CC_FULLOPEN | CC_RGBINIT;
bool success = !!ChooseColor(&cc); bool success = !!ChooseColor(&cc);
DisableOwner(cc.hwndOwner); DisableOwner(cc.hwndOwner);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&ColorChooserDialog::DidCloseDialog, this, success, base::Bind(&ColorChooserDialog::DidCloseDialog, this, success,
skia::COLORREFToSkColor(cc.rgbResult), params.run_state)); skia::COLORREFToSkColor(cc.rgbResult), params.run_state));
} }

View file

@ -21,8 +21,7 @@ class ColorChooserWin : public content::ColorChooser,
static ColorChooserWin* Open(content::WebContents* web_contents, static ColorChooserWin* Open(content::WebContents* web_contents,
SkColor initial_color); SkColor initial_color);
ColorChooserWin(content::WebContents* web_contents, ColorChooserWin(content::WebContents* web_contents, SkColor initial_color);
SkColor initial_color);
~ColorChooserWin(); ~ColorChooserWin();
// content::ColorChooser overrides: // content::ColorChooser overrides:
@ -58,13 +57,12 @@ ColorChooserWin::ColorChooserWin(content::WebContents* web_contents,
SkColor initial_color) SkColor initial_color)
: web_contents_(web_contents) { : web_contents_(web_contents) {
gfx::NativeWindow owning_window = web_contents->GetRenderViewHost() gfx::NativeWindow owning_window = web_contents->GetRenderViewHost()
->GetWidget() ->GetWidget()
->GetView() ->GetView()
->GetNativeView() ->GetNativeView()
->GetToplevelWindow(); ->GetToplevelWindow();
color_chooser_dialog_ = new ColorChooserDialog(this, color_chooser_dialog_ =
initial_color, new ColorChooserDialog(this, initial_color, owning_window);
owning_window);
} }
ColorChooserWin::~ColorChooserWin() { ColorChooserWin::~ColorChooserWin() {

View file

@ -45,24 +45,19 @@ GlobalMenuBarRegistrarX11::GlobalMenuBarRegistrarX11()
// even when |connection_type| is set to SHARED. // even when |connection_type| is set to SHARED.
g_dbus_proxy_new_for_bus( g_dbus_proxy_new_for_bus(
G_BUS_TYPE_SESSION, G_BUS_TYPE_SESSION,
static_cast<GDBusProxyFlags>( static_cast<GDBusProxyFlags>(G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES | G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS |
G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS | G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START),
G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START), nullptr, kAppMenuRegistrarName, kAppMenuRegistrarPath,
nullptr,
kAppMenuRegistrarName,
kAppMenuRegistrarPath,
kAppMenuRegistrarName, kAppMenuRegistrarName,
nullptr, // TODO: Probalby want a real cancelable. nullptr, // TODO: Probalby want a real cancelable.
static_cast<GAsyncReadyCallback>(OnProxyCreatedThunk), static_cast<GAsyncReadyCallback>(OnProxyCreatedThunk), this);
this);
} }
GlobalMenuBarRegistrarX11::~GlobalMenuBarRegistrarX11() { GlobalMenuBarRegistrarX11::~GlobalMenuBarRegistrarX11() {
if (registrar_proxy_) { if (registrar_proxy_) {
g_signal_handlers_disconnect_by_func( g_signal_handlers_disconnect_by_func(
registrar_proxy_, registrar_proxy_, reinterpret_cast<void*>(OnNameOwnerChangedThunk),
reinterpret_cast<void*>(OnNameOwnerChangedThunk),
this); this);
g_object_unref(registrar_proxy_); g_object_unref(registrar_proxy_);
} }
@ -72,7 +67,7 @@ void GlobalMenuBarRegistrarX11::RegisterXID(unsigned long xid) {
DCHECK(registrar_proxy_); DCHECK(registrar_proxy_);
std::string path = atom::GlobalMenuBarX11::GetPathForWindow(xid); std::string path = atom::GlobalMenuBarX11::GetPathForWindow(xid);
ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/314087 ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/314087
// TODO(erg): The mozilla implementation goes to a lot of callback trouble // TODO(erg): The mozilla implementation goes to a lot of callback trouble
// just to make sure that they react to make sure there's some sort of // just to make sure that they react to make sure there's some sort of
// cancelable object; including making a whole callback just to handle the // cancelable object; including making a whole callback just to handle the
@ -80,20 +75,16 @@ void GlobalMenuBarRegistrarX11::RegisterXID(unsigned long xid) {
// //
// I don't see any reason why we should care if "RegisterWindow" completes or // I don't see any reason why we should care if "RegisterWindow" completes or
// not. // not.
g_dbus_proxy_call(registrar_proxy_, g_dbus_proxy_call(registrar_proxy_, "RegisterWindow",
"RegisterWindow",
g_variant_new("(uo)", xid, path.c_str()), g_variant_new("(uo)", xid, path.c_str()),
G_DBUS_CALL_FLAGS_NONE, -1, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, nullptr, nullptr);
nullptr,
nullptr,
nullptr);
} }
void GlobalMenuBarRegistrarX11::UnregisterXID(unsigned long xid) { void GlobalMenuBarRegistrarX11::UnregisterXID(unsigned long xid) {
DCHECK(registrar_proxy_); DCHECK(registrar_proxy_);
std::string path = atom::GlobalMenuBarX11::GetPathForWindow(xid); std::string path = atom::GlobalMenuBarX11::GetPathForWindow(xid);
ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/314087 ANNOTATE_SCOPED_MEMORY_LEAK; // http://crbug.com/314087
// TODO(erg): The mozilla implementation goes to a lot of callback trouble // TODO(erg): The mozilla implementation goes to a lot of callback trouble
// just to make sure that they react to make sure there's some sort of // just to make sure that they react to make sure there's some sort of
// cancelable object; including making a whole callback just to handle the // cancelable object; including making a whole callback just to handle the
@ -101,13 +92,9 @@ void GlobalMenuBarRegistrarX11::UnregisterXID(unsigned long xid) {
// //
// I don't see any reason why we should care if "UnregisterWindow" completes // I don't see any reason why we should care if "UnregisterWindow" completes
// or not. // or not.
g_dbus_proxy_call(registrar_proxy_, g_dbus_proxy_call(registrar_proxy_, "UnregisterWindow",
"UnregisterWindow", g_variant_new("(u)", xid), G_DBUS_CALL_FLAGS_NONE, -1,
g_variant_new("(u)", xid), nullptr, nullptr, nullptr);
G_DBUS_CALL_FLAGS_NONE, -1,
nullptr,
nullptr,
nullptr);
} }
void GlobalMenuBarRegistrarX11::OnProxyCreated(GObject* source, void GlobalMenuBarRegistrarX11::OnProxyCreated(GObject* source,

View file

@ -193,8 +193,8 @@ bool PathProvider(int key, base::FilePath* result) {
#else #else
if (!GetUserDownloadsDirectory(&cur)) if (!GetUserDownloadsDirectory(&cur))
return false; return false;
// Do not create the download directory here, we have done it twice now // Do not create the download directory here, we have done it twice now
// and annoyed a lot of users. // and annoyed a lot of users.
#endif #endif
break; break;
case chrome::DIR_CRASH_DUMPS: case chrome::DIR_CRASH_DUMPS:
@ -383,7 +383,7 @@ bool PathProvider(int key, base::FilePath* result) {
if (base::mac::AmIBundled()) { if (base::mac::AmIBundled()) {
cur = base::mac::FrameworkBundlePath(); cur = base::mac::FrameworkBundlePath();
cur = cur.Append(FILE_PATH_LITERAL("Resources")) cur = cur.Append(FILE_PATH_LITERAL("Resources"))
.Append(FILE_PATH_LITERAL("resources.pak")); .Append(FILE_PATH_LITERAL("resources.pak"));
break; break;
} }
#elif defined(OS_ANDROID) #elif defined(OS_ANDROID)
@ -401,7 +401,7 @@ bool PathProvider(int key, base::FilePath* result) {
if (!PathService::Get(base::DIR_MODULE, &cur)) if (!PathService::Get(base::DIR_MODULE, &cur))
return false; return false;
cur = cur.Append(FILE_PATH_LITERAL("resources")) cur = cur.Append(FILE_PATH_LITERAL("resources"))
.Append(FILE_PATH_LITERAL("extension")); .Append(FILE_PATH_LITERAL("extension"));
break; break;
#if defined(OS_CHROMEOS) #if defined(OS_CHROMEOS)
case chrome::DIR_CHROMEOS_WALLPAPERS: case chrome::DIR_CHROMEOS_WALLPAPERS:
@ -516,8 +516,8 @@ bool PathProvider(int key, base::FilePath* result) {
return false; return false;
cur = cur.Append(FILE_PATH_LITERAL("Google")) cur = cur.Append(FILE_PATH_LITERAL("Google"))
.Append(FILE_PATH_LITERAL("Chrome")) .Append(FILE_PATH_LITERAL("Chrome"))
.Append(FILE_PATH_LITERAL("External Extensions")); .Append(FILE_PATH_LITERAL("External Extensions"));
create_dir = false; create_dir = false;
#else #else
if (!PathService::Get(base::DIR_MODULE, &cur)) if (!PathService::Get(base::DIR_MODULE, &cur))
@ -543,19 +543,19 @@ bool PathProvider(int key, base::FilePath* result) {
case chrome::DIR_NATIVE_MESSAGING: case chrome::DIR_NATIVE_MESSAGING:
#if defined(OS_MACOSX) #if defined(OS_MACOSX)
#if defined(GOOGLE_CHROME_BUILD) #if defined(GOOGLE_CHROME_BUILD)
cur = base::FilePath(FILE_PATH_LITERAL( cur = base::FilePath(
"/Library/Google/Chrome/NativeMessagingHosts")); FILE_PATH_LITERAL("/Library/Google/Chrome/NativeMessagingHosts"));
#else #else
cur = base::FilePath(FILE_PATH_LITERAL( cur = base::FilePath(FILE_PATH_LITERAL(
"/Library/Application Support/Chromium/NativeMessagingHosts")); "/Library/Application Support/Chromium/NativeMessagingHosts"));
#endif #endif
#else // defined(OS_MACOSX) #else // defined(OS_MACOSX)
#if defined(GOOGLE_CHROME_BUILD) #if defined(GOOGLE_CHROME_BUILD)
cur = base::FilePath(FILE_PATH_LITERAL( cur = base::FilePath(
"/etc/opt/chrome/native-messaging-hosts")); FILE_PATH_LITERAL("/etc/opt/chrome/native-messaging-hosts"));
#else #else
cur = base::FilePath(FILE_PATH_LITERAL( cur = base::FilePath(
"/etc/chromium/native-messaging-hosts")); FILE_PATH_LITERAL("/etc/chromium/native-messaging-hosts"));
#endif #endif
#endif // !defined(OS_MACOSX) #endif // !defined(OS_MACOSX)
break; break;
@ -589,8 +589,7 @@ bool PathProvider(int key, base::FilePath* result) {
// TODO(bauerb): http://crbug.com/259796 // TODO(bauerb): http://crbug.com/259796
base::ThreadRestrictions::ScopedAllowIO allow_io; base::ThreadRestrictions::ScopedAllowIO allow_io;
if (create_dir && !base::PathExists(cur) && if (create_dir && !base::PathExists(cur) && !base::CreateDirectory(cur))
!base::CreateDirectory(cur))
return false; return false;
*result = cur; *result = cur;

View file

@ -90,8 +90,8 @@ enum {
// succeed no matter the file exists or not. // succeed no matter the file exists or not.
FILE_FLASH_SYSTEM_PLUGIN, // Full path to the system version of NPAPI FILE_FLASH_SYSTEM_PLUGIN, // Full path to the system version of NPAPI
// Flash plugin, downloadable from Adobe // Flash plugin, downloadable from Adobe
// website. Querying this path might succeed no // website. Querying this path might succeed no
// matter the file exists or not. // matter the file exists or not.
FILE_NACL_PLUGIN, // Full path to the internal NaCl plugin file. FILE_NACL_PLUGIN, // Full path to the internal NaCl plugin file.
DIR_PNACL_BASE, // Full path to the base dir for PNaCl. DIR_PNACL_BASE, // Full path to the base dir for PNaCl.
DIR_PNACL_COMPONENT, // Full path to the latest PNaCl version DIR_PNACL_COMPONENT, // Full path to the latest PNaCl version

View file

@ -62,9 +62,8 @@ bool GetUserMediaDirectory(const std::string& xdg_name,
// (This also helps us sidestep issues with other apps grabbing ~/.chromium .) // (This also helps us sidestep issues with other apps grabbing ~/.chromium .)
bool GetDefaultUserDataDirectory(base::FilePath* result) { bool GetDefaultUserDataDirectory(base::FilePath* result) {
std::unique_ptr<base::Environment> env(base::Environment::Create()); std::unique_ptr<base::Environment> env(base::Environment::Create());
base::FilePath config_dir(GetXDGDirectory(env.get(), base::FilePath config_dir(
kXdgConfigHomeEnvVar, GetXDGDirectory(env.get(), kXdgConfigHomeEnvVar, kDotConfigDir));
kDotConfigDir));
#if defined(GOOGLE_CHROME_BUILD) #if defined(GOOGLE_CHROME_BUILD)
*result = config_dir.Append("google-chrome"); *result = config_dir.Append("google-chrome");
#else #else
@ -91,9 +90,8 @@ void GetUserCacheDirectory(const base::FilePath& profile_dir,
base::FilePath cache_dir; base::FilePath cache_dir;
if (!PathService::Get(base::DIR_CACHE, &cache_dir)) if (!PathService::Get(base::DIR_CACHE, &cache_dir))
return; return;
base::FilePath config_dir(GetXDGDirectory(env.get(), base::FilePath config_dir(
kXdgConfigHomeEnvVar, GetXDGDirectory(env.get(), kXdgConfigHomeEnvVar, kDotConfigDir));
kDotConfigDir));
if (!config_dir.AppendRelativePath(profile_dir, &cache_dir)) if (!config_dir.AppendRelativePath(profile_dir, &cache_dir))
return; return;

View file

@ -4,11 +4,11 @@
#include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_paths_internal.h"
#include <windows.h>
#include <knownfolders.h> #include <knownfolders.h>
#include <shellapi.h> #include <shellapi.h>
#include <shlobj.h> #include <shlobj.h>
#include <shobjidl.h> #include <shobjidl.h>
#include <windows.h>
#include "base/files/file_path.h" #include "base/files/file_path.h"
#include "base/path_service.h" #include "base/path_service.h"
@ -28,8 +28,8 @@ bool GetUserDirectory(int csidl_folder, base::FilePath* result) {
// so we don't bother handling it. // so we don't bother handling it.
wchar_t path_buf[MAX_PATH]; wchar_t path_buf[MAX_PATH];
path_buf[0] = 0; path_buf[0] = 0;
if (FAILED(SHGetFolderPath(NULL, csidl_folder, NULL, if (FAILED(SHGetFolderPath(NULL, csidl_folder, NULL, SHGFP_TYPE_CURRENT,
SHGFP_TYPE_CURRENT, path_buf))) { path_buf))) {
return false; return false;
} }
*result = base::FilePath(path_buf); *result = base::FilePath(path_buf);
@ -68,8 +68,8 @@ bool GetUserDownloadsDirectorySafe(base::FilePath* result) {
// relocated to point to a "dangerous" folder, callers should validate that the // relocated to point to a "dangerous" folder, callers should validate that the
// returned path is not dangerous before using it. // returned path is not dangerous before using it.
bool GetUserDownloadsDirectory(base::FilePath* result) { bool GetUserDownloadsDirectory(base::FilePath* result) {
typedef HRESULT (WINAPI *GetKnownFolderPath)( typedef HRESULT(WINAPI * GetKnownFolderPath)(REFKNOWNFOLDERID, DWORD, HANDLE,
REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*); PWSTR*);
GetKnownFolderPath f = reinterpret_cast<GetKnownFolderPath>( GetKnownFolderPath f = reinterpret_cast<GetKnownFolderPath>(
GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetKnownFolderPath")); GetProcAddress(GetModuleHandle(L"shell32.dll"), "SHGetKnownFolderPath"));
base::win::ScopedCoMem<wchar_t> path_buf; base::win::ScopedCoMem<wchar_t> path_buf;

View file

@ -26,8 +26,7 @@ PrintMsg_Print_Params::PrintMsg_Print_Params()
display_header_footer(false), display_header_footer(false),
title(), title(),
url(), url(),
should_print_backgrounds(false) { should_print_backgrounds(false) {}
}
PrintMsg_Print_Params::~PrintMsg_Print_Params() {} PrintMsg_Print_Params::~PrintMsg_Print_Params() {}
@ -53,9 +52,7 @@ void PrintMsg_Print_Params::Reset() {
should_print_backgrounds = false; should_print_backgrounds = false;
} }
PrintMsg_PrintPages_Params::PrintMsg_PrintPages_Params() PrintMsg_PrintPages_Params::PrintMsg_PrintPages_Params() : pages() {}
: pages() {
}
PrintMsg_PrintPages_Params::~PrintMsg_PrintPages_Params() {} PrintMsg_PrintPages_Params::~PrintMsg_PrintPages_Params() {}

View file

@ -5,26 +5,14 @@
#include "chrome/common/tts_utterance_request.h" #include "chrome/common/tts_utterance_request.h"
TtsUtteranceRequest::TtsUtteranceRequest() TtsUtteranceRequest::TtsUtteranceRequest()
: id(0), : id(0), volume(1.0), rate(1.0), pitch(1.0) {}
volume(1.0),
rate(1.0),
pitch(1.0) {
}
TtsUtteranceRequest::~TtsUtteranceRequest() { TtsUtteranceRequest::~TtsUtteranceRequest() {}
}
TtsVoice::TtsVoice() TtsVoice::TtsVoice() : local_service(true), is_default(false) {}
: local_service(true),
is_default(false) {
}
TtsVoice::~TtsVoice() { TtsVoice::~TtsVoice() {}
}
TtsUtteranceResponse::TtsUtteranceResponse() TtsUtteranceResponse::TtsUtteranceResponse() : id(0) {}
: id(0) {
}
TtsUtteranceResponse::~TtsUtteranceResponse() { TtsUtteranceResponse::~TtsUtteranceResponse() {}
}

View file

@ -9,5 +9,5 @@
const char kWidevineCdmPluginExtension[] = ""; const char kWidevineCdmPluginExtension[] = "";
const int32_t kWidevineCdmPluginPermissions = ppapi::PERMISSION_DEV | const int32_t kWidevineCdmPluginPermissions =
ppapi::PERMISSION_PRIVATE; ppapi::PERMISSION_DEV | ppapi::PERMISSION_PRIVATE;

View file

@ -44,9 +44,7 @@ static bool IsPepperCdmAvailable(
bool is_available = false; bool is_available = false;
content::RenderThread::Get()->Send( content::RenderThread::Get()->Send(
new ChromeViewHostMsg_IsInternalPluginAvailableForMimeType( new ChromeViewHostMsg_IsInternalPluginAvailableForMimeType(
pepper_type, pepper_type, &is_available, additional_param_names,
&is_available,
additional_param_names,
additional_param_values)); additional_param_values));
return is_available; return is_available;
@ -181,8 +179,7 @@ void GetSupportedCodecsForPepperCdm(
base::ASCIIToUTF16(kCdmSupportedCodecsParamName)) { base::ASCIIToUTF16(kCdmSupportedCodecsParamName)) {
const base::string16& codecs_string16 = additional_param_values[i]; const base::string16& codecs_string16 = additional_param_values[i];
std::string codecs_string; std::string codecs_string;
if (!base::UTF16ToUTF8(codecs_string16.c_str(), if (!base::UTF16ToUTF8(codecs_string16.c_str(), codecs_string16.length(),
codecs_string16.length(),
&codecs_string)) { &codecs_string)) {
DLOG(WARNING) << "Non-UTF-8 codecs string."; DLOG(WARNING) << "Non-UTF-8 codecs string.";
// Continue using the best effort conversion. // Continue using the best effort conversion.
@ -206,8 +203,7 @@ static void AddPepperBasedWidevine(
std::vector<base::string16> additional_param_names; std::vector<base::string16> additional_param_names;
std::vector<base::string16> additional_param_values; std::vector<base::string16> additional_param_values;
if (!IsPepperCdmAvailable(kWidevineCdmPluginMimeType, if (!IsPepperCdmAvailable(kWidevineCdmPluginMimeType, &additional_param_names,
&additional_param_names,
&additional_param_values)) { &additional_param_values)) {
DVLOG(1) << "Widevine CDM is not currently available."; DVLOG(1) << "Widevine CDM is not currently available.";
return; return;
@ -215,8 +211,7 @@ static void AddPepperBasedWidevine(
std::vector<std::string> codecs; std::vector<std::string> codecs;
GetSupportedCodecsForPepperCdm(additional_param_names, GetSupportedCodecsForPepperCdm(additional_param_names,
additional_param_values, additional_param_values, &codecs);
&codecs);
SupportedCodecs supported_codecs = media::EME_CODEC_NONE; SupportedCodecs supported_codecs = media::EME_CODEC_NONE;
@ -254,15 +249,15 @@ static void AddPepperBasedWidevine(
NOT_SUPPORTED, // Persistent-release-message. NOT_SUPPORTED, // Persistent-release-message.
media::EmeFeatureSupport::REQUESTABLE, // Persistent state. media::EmeFeatureSupport::REQUESTABLE, // Persistent state.
media::EmeFeatureSupport::REQUESTABLE)); // Distinctive identifier. media::EmeFeatureSupport::REQUESTABLE)); // Distinctive identifier.
#else // (Desktop) #else // (Desktop)
Robustness::SW_SECURE_CRYPTO, // Maximum audio robustness. Robustness::SW_SECURE_CRYPTO, // Maximum audio robustness.
Robustness::SW_SECURE_DECODE, // Maximum video robustness. Robustness::SW_SECURE_DECODE, // Maximum video robustness.
media::EmeSessionTypeSupport::NOT_SUPPORTED, // persistent-license. media::EmeSessionTypeSupport::NOT_SUPPORTED, // persistent-license.
media::EmeSessionTypeSupport:: media::EmeSessionTypeSupport::
NOT_SUPPORTED, // persistent-release-message. NOT_SUPPORTED, // persistent-release-message.
media::EmeFeatureSupport::REQUESTABLE, // Persistent state. media::EmeFeatureSupport::REQUESTABLE, // Persistent state.
media::EmeFeatureSupport::NOT_SUPPORTED)); // Distinctive identifier. media::EmeFeatureSupport::NOT_SUPPORTED)); // Distinctive identifier.
#endif // defined(OS_CHROMEOS) #endif // defined(OS_CHROMEOS)
} }
#endif // defined(WIDEVINE_CDM_AVAILABLE) #endif // defined(WIDEVINE_CDM_AVAILABLE)
#endif // BUILDFLAG(ENABLE_LIBRARY_CDMS) #endif // BUILDFLAG(ENABLE_LIBRARY_CDMS)

View file

@ -28,7 +28,8 @@ ChromeRendererPepperHostFactory::ChromeRendererPepperHostFactory(
ChromeRendererPepperHostFactory::~ChromeRendererPepperHostFactory() {} ChromeRendererPepperHostFactory::~ChromeRendererPepperHostFactory() {}
std::unique_ptr<ResourceHost> ChromeRendererPepperHostFactory::CreateResourceHost( std::unique_ptr<ResourceHost>
ChromeRendererPepperHostFactory::CreateResourceHost(
ppapi::host::PpapiHost* host, ppapi::host::PpapiHost* host,
PP_Resource resource, PP_Resource resource,
PP_Instance instance, PP_Instance instance,

View file

@ -32,10 +32,8 @@ PepperFlashFontFileHost::PepperFlashFontFileHost(
fd_.reset(content::MatchFontWithFallback( fd_.reset(content::MatchFontWithFallback(
description.face.c_str(), description.face.c_str(),
description.weight >= PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD, description.weight >= PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD,
description.italic, description.italic, charset, PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT));
charset, #elif defined(OS_WIN) // defined(OS_LINUX) || defined(OS_OPENBSD)
PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT));
#elif defined(OS_WIN) // defined(OS_LINUX) || defined(OS_OPENBSD)
int weight = description.weight; int weight = description.weight;
if (weight == FW_DONTCARE) if (weight == FW_DONTCARE)
weight = SkFontStyle::kNormal_Weight; weight = SkFontStyle::kNormal_Weight;
@ -45,7 +43,7 @@ PepperFlashFontFileHost::PepperFlashFontFileHost(
sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault());
typeface_ = sk_sp<SkTypeface>( typeface_ = sk_sp<SkTypeface>(
font_mgr->matchFamilyStyle(description.face.c_str(), style)); font_mgr->matchFamilyStyle(description.face.c_str(), style));
#endif // defined(OS_WIN) #endif // defined(OS_WIN)
} }
PepperFlashFontFileHost::~PepperFlashFontFileHost() {} PepperFlashFontFileHost::~PepperFlashFontFileHost() {}
@ -67,7 +65,7 @@ bool PepperFlashFontFileHost::GetFontData(uint32_t table,
int fd = fd_.get(); int fd = fd_.get();
if (fd != -1) if (fd != -1)
result = content::GetFontTable(fd, table, 0 /* offset */, result = content::GetFontTable(fd, table, 0 /* offset */,
reinterpret_cast<uint8_t*>(buffer), length); reinterpret_cast<uint8_t*>(buffer), length);
#elif defined(OS_WIN) #elif defined(OS_WIN)
if (typeface_) { if (typeface_) {
table = base::ByteSwap(table); table = base::ByteSwap(table);
@ -92,14 +90,14 @@ int32_t PepperFlashFontFileHost::OnGetFontTable(
int32_t result = PP_ERROR_FAILED; int32_t result = PP_ERROR_FAILED;
size_t length = 0; size_t length = 0;
if (GetFontData(table, NULL, &length)) { if (GetFontData(table, NULL, &length)) {
contents.resize(length); contents.resize(length);
uint8_t* contents_ptr = uint8_t* contents_ptr =
reinterpret_cast<uint8_t*>(const_cast<char*>(contents.c_str())); reinterpret_cast<uint8_t*>(const_cast<char*>(contents.c_str()));
if (GetFontData(table, contents_ptr, &length)) { if (GetFontData(table, contents_ptr, &length)) {
result = PP_OK; result = PP_OK;
} else { } else {
contents.clear(); contents.clear();
} }
} }
context->reply_msg = PpapiPluginMsg_FlashFontFile_GetFontTableReply(contents); context->reply_msg = PpapiPluginMsg_FlashFontFile_GetFontTableReply(contents);

View file

@ -26,8 +26,7 @@ int32_t PepperFlashFullscreenHost::OnResourceMessageReceived(
ppapi::host::HostMessageContext* context) { ppapi::host::HostMessageContext* context) {
PPAPI_BEGIN_MESSAGE_MAP(PepperFlashFullscreenHost, msg) PPAPI_BEGIN_MESSAGE_MAP(PepperFlashFullscreenHost, msg)
PPAPI_DISPATCH_HOST_RESOURCE_CALL( PPAPI_DISPATCH_HOST_RESOURCE_CALL(
PpapiHostMsg_FlashFullscreen_SetFullscreen, PpapiHostMsg_FlashFullscreen_SetFullscreen, OnSetFullscreen)
OnSetFullscreen)
PPAPI_END_MESSAGE_MAP() PPAPI_END_MESSAGE_MAP()
return PP_ERROR_FAILED; return PP_ERROR_FAILED;
} }

View file

@ -79,8 +79,8 @@ bool ConvertMenuData(const PP_Flash_Menu* in_menu,
item.enabled = PP_ToBool(in_menu->items[i].enabled); item.enabled = PP_ToBool(in_menu->items[i].enabled);
item.checked = PP_ToBool(in_menu->items[i].checked); item.checked = PP_ToBool(in_menu->items[i].checked);
if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU) { if (type == PP_FLASH_MENUITEM_TYPE_SUBMENU) {
if (!ConvertMenuData( if (!ConvertMenuData(in_menu->items[i].submenu, depth + 1, &item.submenu,
in_menu->items[i].submenu, depth + 1, &item.submenu, menu_id_map)) menu_id_map))
return false; return false;
} }
@ -194,8 +194,7 @@ void PepperFlashMenuHost::OnMenuClosed(int request_id) {
void PepperFlashMenuHost::SendMenuReply(int32_t result, int action) { void PepperFlashMenuHost::SendMenuReply(int32_t result, int action) {
ppapi::host::ReplyMessageContext reply_context( ppapi::host::ReplyMessageContext reply_context(
ppapi::proxy::ResourceMessageReplyParams(pp_resource(), 0), ppapi::proxy::ResourceMessageReplyParams(pp_resource(), 0), NULL,
NULL,
MSG_ROUTING_NONE); MSG_ROUTING_NONE);
reply_context.params.set_result(result); reply_context.params.set_result(result);
host()->SendReply(reply_context, PpapiPluginMsg_FlashMenu_ShowReply(action)); host()->SendReply(reply_context, PpapiPluginMsg_FlashMenu_ShowReply(action));

View file

@ -97,7 +97,7 @@ enum FlashNavigateUsage {
FLASH_NAVIGATE_USAGE_ENUM_COUNT FLASH_NAVIGATE_USAGE_ENUM_COUNT
}; };
static base::LazyInstance<std::map<std::string, FlashNavigateUsage> >:: static base::LazyInstance<std::map<std::string, FlashNavigateUsage>>::
DestructorAtExit g_rejected_headers = LAZY_INSTANCE_INITIALIZER; DestructorAtExit g_rejected_headers = LAZY_INSTANCE_INITIALIZER;
bool IsSimpleHeader(const std::string& lower_case_header_name, bool IsSimpleHeader(const std::string& lower_case_header_name,
@ -112,11 +112,8 @@ bool IsSimpleHeader(const std::string& lower_case_header_name,
std::string lower_case_mime_type; std::string lower_case_mime_type;
std::string lower_case_charset; std::string lower_case_charset;
bool had_charset = false; bool had_charset = false;
net::HttpUtil::ParseContentType(header_value, net::HttpUtil::ParseContentType(header_value, &lower_case_mime_type,
&lower_case_mime_type, &lower_case_charset, &had_charset, NULL);
&lower_case_charset,
&had_charset,
NULL);
return lower_case_mime_type == "application/x-www-form-urlencoded" || return lower_case_mime_type == "application/x-www-form-urlencoded" ||
lower_case_mime_type == "multipart/form-data" || lower_case_mime_type == "multipart/form-data" ||
lower_case_mime_type == "text/plain"; lower_case_mime_type == "text/plain";
@ -127,8 +124,8 @@ bool IsSimpleHeader(const std::string& lower_case_header_name,
void RecordFlashNavigateUsage(FlashNavigateUsage usage) { void RecordFlashNavigateUsage(FlashNavigateUsage usage) {
DCHECK_NE(FLASH_NAVIGATE_USAGE_ENUM_COUNT, usage); DCHECK_NE(FLASH_NAVIGATE_USAGE_ENUM_COUNT, usage);
UMA_HISTOGRAM_ENUMERATION( UMA_HISTOGRAM_ENUMERATION("Plugin.FlashNavigateUsage", usage,
"Plugin.FlashNavigateUsage", usage, FLASH_NAVIGATE_USAGE_ENUM_COUNT); FLASH_NAVIGATE_USAGE_ENUM_COUNT);
} }
} // namespace } // namespace
@ -277,8 +274,8 @@ int32_t PepperFlashRendererHost::OnDrawGlyphs(
y += SkFloatToScalar(params.glyph_advances[i].y); y += SkFloatToScalar(params.glyph_advances[i].y);
} }
canvas->drawPosText( canvas->drawPosText(&params.glyph_indices[0], glyph_count * 2, sk_positions,
&params.glyph_indices[0], glyph_count * 2, sk_positions, paint); paint);
} }
if (needs_unmapping) if (needs_unmapping)
@ -310,12 +307,11 @@ int32_t PepperFlashRendererHost::OnNavigate(
static_cast<FlashNavigateUsage>(i); static_cast<FlashNavigateUsage>(i);
} }
net::HttpUtil::HeadersIterator header_iter( net::HttpUtil::HeadersIterator header_iter(data.headers.begin(),
data.headers.begin(), data.headers.end(), "\n\r"); data.headers.end(), "\n\r");
bool rejected = false; bool rejected = false;
while (header_iter.GetNext()) { while (header_iter.GetNext()) {
std::string lower_case_header_name = std::string lower_case_header_name = base::ToLowerASCII(header_iter.name());
base::ToLowerASCII(header_iter.name());
if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) { if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) {
rejected = true; rejected = true;

View file

@ -83,30 +83,26 @@ PrintMsg_Print_Params GetCssPrintParams(
int margin_top_in_pixels = int margin_top_in_pixels =
ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch); ConvertUnit(page_params.margin_top, dpi, kPixelsPerInch);
int margin_right_in_pixels = ConvertUnit( int margin_right_in_pixels = ConvertUnit(
page_params.page_size.width() - page_params.page_size.width() - page_params.content_size.width() -
page_params.content_size.width() - page_params.margin_left, page_params.margin_left,
dpi, kPixelsPerInch); dpi, kPixelsPerInch);
int margin_bottom_in_pixels = ConvertUnit( int margin_bottom_in_pixels = ConvertUnit(
page_params.page_size.height() - page_params.page_size.height() - page_params.content_size.height() -
page_params.content_size.height() - page_params.margin_top, page_params.margin_top,
dpi, kPixelsPerInch);
int margin_left_in_pixels = ConvertUnit(
page_params.margin_left,
dpi, kPixelsPerInch); dpi, kPixelsPerInch);
int margin_left_in_pixels =
ConvertUnit(page_params.margin_left, dpi, kPixelsPerInch);
if (frame) { if (frame) {
frame->PageSizeAndMarginsInPixels(page_index, frame->PageSizeAndMarginsInPixels(
page_size_in_pixels, page_index, page_size_in_pixels, margin_top_in_pixels,
margin_top_in_pixels, margin_right_in_pixels, margin_bottom_in_pixels, margin_left_in_pixels);
margin_right_in_pixels,
margin_bottom_in_pixels,
margin_left_in_pixels);
} }
double new_content_width = page_size_in_pixels.Width() - double new_content_width = page_size_in_pixels.Width() -
margin_left_in_pixels - margin_right_in_pixels; margin_left_in_pixels - margin_right_in_pixels;
double new_content_height = page_size_in_pixels.Height() - double new_content_height = page_size_in_pixels.Height() -
margin_top_in_pixels - margin_bottom_in_pixels; margin_top_in_pixels - margin_bottom_in_pixels;
// Invalid page size and/or margins. We just use the default setting. // Invalid page size and/or margins. We just use the default setting.
if (new_content_width < 1 || new_content_height < 1) { if (new_content_width < 1 || new_content_height < 1) {
@ -120,7 +116,7 @@ PrintMsg_Print_Params GetCssPrintParams(
ConvertUnit(page_size_in_pixels.Height(), kPixelsPerInch, dpi)); ConvertUnit(page_size_in_pixels.Height(), kPixelsPerInch, dpi));
page_css_params.content_size = page_css_params.content_size =
gfx::Size(ConvertUnit(new_content_width, kPixelsPerInch, dpi), gfx::Size(ConvertUnit(new_content_width, kPixelsPerInch, dpi),
ConvertUnit(new_content_height, kPixelsPerInch, dpi)); ConvertUnit(new_content_height, kPixelsPerInch, dpi));
page_css_params.margin_top = page_css_params.margin_top =
ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi); ConvertUnit(margin_top_in_pixels, kPixelsPerInch, dpi);
@ -160,8 +156,8 @@ double FitPrintParamsToPage(const PrintMsg_Print_Params& page_params,
params_to_fit->margin_left = static_cast<int>( params_to_fit->margin_left = static_cast<int>(
(default_page_size_width - css_page_size_width * scale_factor) / 2 + (default_page_size_width - css_page_size_width * scale_factor) / 2 +
(params_to_fit->margin_left * scale_factor)); (params_to_fit->margin_left * scale_factor));
params_to_fit->content_size = gfx::Size( params_to_fit->content_size = gfx::Size(static_cast<int>(content_width),
static_cast<int>(content_width), static_cast<int>(content_height)); static_cast<int>(content_height));
params_to_fit->page_size = page_params.page_size; params_to_fit->page_size = page_params.page_size;
return scale_factor; return scale_factor;
} }
@ -173,10 +169,10 @@ void CalculatePageLayoutFromPrintParams(
int content_width = params.content_size.width(); int content_width = params.content_size.width();
int content_height = params.content_size.height(); int content_height = params.content_size.height();
int margin_bottom = params.page_size.height() - int margin_bottom =
content_height - params.margin_top; params.page_size.height() - content_height - params.margin_top;
int margin_right = params.page_size.width() - int margin_right =
content_width - params.margin_left; params.page_size.width() - content_width - params.margin_left;
page_layout_in_points->content_width = page_layout_in_points->content_width =
ConvertUnit(content_width, dpi, kPointsPerInch); ConvertUnit(content_width, dpi, kPointsPerInch);
@ -237,8 +233,9 @@ void ComputeWebKitPrintParamsInDesiredDpi(
} }
blink::WebPlugin* GetPlugin(const blink::WebLocalFrame* frame) { blink::WebPlugin* GetPlugin(const blink::WebLocalFrame* frame) {
return frame->GetDocument().IsPluginDocument() ? return frame->GetDocument().IsPluginDocument()
frame->GetDocument().To<blink::WebPluginDocument>().Plugin() : nullptr; ? frame->GetDocument().To<blink::WebPluginDocument>().Plugin()
: nullptr;
} }
bool PrintingNodeOrPdfFrame(const blink::WebLocalFrame* frame, bool PrintingNodeOrPdfFrame(const blink::WebLocalFrame* frame,
@ -264,8 +261,8 @@ PrintMsg_Print_Params CalculatePrintParamsForCss(
bool ignore_css_margins, bool ignore_css_margins,
bool fit_to_page, bool fit_to_page,
double* scale_factor) { double* scale_factor) {
PrintMsg_Print_Params css_params = GetCssPrintParams(frame, page_index, PrintMsg_Print_Params css_params =
page_params); GetCssPrintParams(frame, page_index, page_params);
PrintMsg_Print_Params params = page_params; PrintMsg_Print_Params params = page_params;
EnsureOrientationMatches(css_params, &params); EnsureOrientationMatches(css_params, &params);
@ -282,14 +279,15 @@ PrintMsg_Print_Params CalculatePrintParamsForCss(
// Since we are ignoring the margins, the css page size is no longer // Since we are ignoring the margins, the css page size is no longer
// valid. // valid.
int default_margin_right = params.page_size.width() - int default_margin_right = params.page_size.width() -
params.content_size.width() - params.margin_left; params.content_size.width() - params.margin_left;
int default_margin_bottom = params.page_size.height() - int default_margin_bottom = params.page_size.height() -
params.content_size.height() - params.margin_top; params.content_size.height() -
result_params.content_size = gfx::Size( params.margin_top;
result_params.page_size.width() - result_params.margin_left - result_params.content_size =
default_margin_right, gfx::Size(result_params.page_size.width() - result_params.margin_left -
result_params.page_size.height() - result_params.margin_top - default_margin_right,
default_margin_bottom); result_params.page_size.height() - result_params.margin_top -
default_margin_bottom);
} }
if (fit_to_page) { if (fit_to_page) {
@ -310,8 +308,7 @@ FrameReference::FrameReference() {
Reset(NULL); Reset(NULL);
} }
FrameReference::~FrameReference() { FrameReference::~FrameReference() {}
}
void FrameReference::Reset(blink::WebLocalFrame* frame) { void FrameReference::Reset(blink::WebLocalFrame* frame) {
if (frame) { if (frame) {
@ -370,17 +367,11 @@ class PrepareFrameAndViewForPrint : public blink::WebViewClient,
// Prepares frame for printing. // Prepares frame for printing.
void StartPrinting(); void StartPrinting();
blink::WebLocalFrame* frame() { blink::WebLocalFrame* frame() { return frame_.GetFrame(); }
return frame_.GetFrame();
}
const blink::WebNode& node() const { const blink::WebNode& node() const { return node_to_print_; }
return node_to_print_;
}
int GetExpectedPageCount() const { int GetExpectedPageCount() const { return expected_pages_count_; }
return expected_pages_count_;
}
void FinishPrinting(); void FinishPrinting();
@ -445,12 +436,11 @@ PrepareFrameAndViewForPrint::PrepareFrameAndViewForPrint(
!PrintingNodeOrPdfFrame(frame, node_to_print_)) { !PrintingNodeOrPdfFrame(frame, node_to_print_)) {
bool fit_to_page = ignore_css_margins && bool fit_to_page = ignore_css_margins &&
print_params.print_scaling_option == print_params.print_scaling_option ==
blink::kWebPrintScalingOptionFitToPrintableArea; blink::kWebPrintScalingOptionFitToPrintableArea;
ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_); ComputeWebKitPrintParamsInDesiredDpi(params, &web_print_params_);
frame->PrintBegin(web_print_params_, node_to_print_); frame->PrintBegin(web_print_params_, node_to_print_);
print_params = CalculatePrintParamsForCss(frame, 0, print_params, print_params = CalculatePrintParamsForCss(
ignore_css_margins, fit_to_page, frame, 0, print_params, ignore_css_margins, fit_to_page, NULL);
NULL);
frame->PrintEnd(); frame->PrintEnd();
} }
ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_); ComputeWebKitPrintParamsInDesiredDpi(print_params, &web_print_params_);
@ -486,7 +476,6 @@ void PrepareFrameAndViewForPrint::ResizeForPrinting() {
web_view->Resize(print_layout_size); web_view->Resize(print_layout_size);
} }
void PrepareFrameAndViewForPrint::StartPrinting() { void PrepareFrameAndViewForPrint::StartPrinting() {
ResizeForPrinting(); ResizeForPrinting();
blink::WebView* web_view = frame_.view(); blink::WebView* web_view = frame_.view();
@ -525,8 +514,8 @@ void PrepareFrameAndViewForPrint::CopySelection(
blink::WebView::Create(this, blink::kWebPageVisibilityStateVisible); blink::WebView::Create(this, blink::kWebPageVisibilityStateVisible);
owns_web_view_ = true; owns_web_view_ = true;
content::RenderView::ApplyWebPreferences(prefs, web_view); content::RenderView::ApplyWebPreferences(prefs, web_view);
blink::WebLocalFrame* main_frame = blink::WebLocalFrame::CreateMainFrame( blink::WebLocalFrame* main_frame =
web_view, this, nullptr, nullptr); blink::WebLocalFrame::CreateMainFrame(web_view, this, nullptr, nullptr);
blink::WebFrameWidget::Create(this, main_frame); blink::WebFrameWidget::Create(this, main_frame);
frame_.Reset(web_view->MainFrame()->ToWebLocalFrame()); frame_.Reset(web_view->MainFrame()->ToWebLocalFrame());
node_to_print_.Reset(); node_to_print_.Reset();
@ -557,8 +546,7 @@ blink::WebLocalFrame* PrepareFrameAndViewForPrint::CreateChildFrame(
blink::WebSandboxFlags sandbox_flags, blink::WebSandboxFlags sandbox_flags,
const blink::WebParsedFeaturePolicy& container_policy, const blink::WebParsedFeaturePolicy& container_policy,
const blink::WebFrameOwnerProperties& frame_owner_properties) { const blink::WebFrameOwnerProperties& frame_owner_properties) {
blink::WebLocalFrame* frame = parent->CreateLocalChild( blink::WebLocalFrame* frame = parent->CreateLocalChild(scope, this, nullptr);
scope, this, nullptr);
return frame; return frame;
} }
@ -613,8 +601,7 @@ PrintWebViewHelper::PrintWebViewHelper(content::RenderFrame* render_frame)
is_loading_(false), is_loading_(false),
is_scripted_preview_delayed_(false), is_scripted_preview_delayed_(false),
ipc_nesting_level_(0), ipc_nesting_level_(0),
weak_ptr_factory_(this) { weak_ptr_factory_(this) {}
}
PrintWebViewHelper::~PrintWebViewHelper() {} PrintWebViewHelper::~PrintWebViewHelper() {}
@ -639,7 +626,7 @@ bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone) IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview) IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
IPC_MESSAGE_UNHANDLED(handled = false) IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP() IPC_END_MESSAGE_MAP()
--ipc_nesting_level_; --ipc_nesting_level_;
return handled; return handled;
@ -650,9 +637,10 @@ void PrintWebViewHelper::OnDestruct() {
} }
#if !defined(DISABLE_BASIC_PRINTING) #if !defined(DISABLE_BASIC_PRINTING)
void PrintWebViewHelper::OnPrintPages(bool silent, bool print_background, void PrintWebViewHelper::OnPrintPages(bool silent,
bool print_background,
const base::string16& device_name) { const base::string16& device_name) {
if (ipc_nesting_level_> 1) if (ipc_nesting_level_ > 1)
return; return;
blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
@ -665,11 +653,9 @@ void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
gfx::Size* page_size, gfx::Size* page_size,
gfx::Rect* content_area) { gfx::Rect* content_area) {
*page_size = gfx::Size( *page_size = gfx::Size(
page_layout_in_points.content_width + page_layout_in_points.content_width + page_layout_in_points.margin_right +
page_layout_in_points.margin_right +
page_layout_in_points.margin_left, page_layout_in_points.margin_left,
page_layout_in_points.content_height + page_layout_in_points.content_height + page_layout_in_points.margin_top +
page_layout_in_points.margin_top +
page_layout_in_points.margin_bottom); page_layout_in_points.margin_bottom);
*content_area = gfx::Rect(page_layout_in_points.margin_left, *content_area = gfx::Rect(page_layout_in_points.margin_left,
page_layout_in_points.margin_top, page_layout_in_points.margin_top,
@ -896,9 +882,9 @@ void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
case FAIL_PREVIEW: case FAIL_PREVIEW:
case INVALID_SETTINGS: case INVALID_SETTINGS:
if (print_pages_params_) { if (print_pages_params_) {
Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), Send(new PrintHostMsg_PrintPreviewFailed(
print_pages_params_->params.document_cookie, routing_id(), print_pages_params_->params.document_cookie,
print_pages_params_->params.preview_request_id)); print_pages_params_->params.preview_request_id));
} }
break; break;
} }
@ -929,9 +915,8 @@ void PrintWebViewHelper::PrintPages() {
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
// TODO(vitalybuka): should be page_count or valid pages from params.pages. // TODO(vitalybuka): should be page_count or valid pages from params.pages.
// See http://crbug.com/161576 // See http://crbug.com/161576
Send(new PrintHostMsg_DidGetPrintedPagesCount(routing_id(), Send(new PrintHostMsg_DidGetPrintedPagesCount(
print_params.document_cookie, routing_id(), print_params.document_cookie, page_count));
page_count));
#endif // !defined(OS_CHROMEOS) #endif // !defined(OS_CHROMEOS)
if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) { if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) {
@ -1018,10 +1003,11 @@ bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size,
return result; return result;
} }
bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, bool PrintWebViewHelper::CalculateNumberOfPages(
const blink::WebNode& node, blink::WebLocalFrame* frame,
int* number_of_pages, const blink::WebNode& node,
const base::string16& device_name) { int* number_of_pages,
const base::string16& device_name) {
DCHECK(frame); DCHECK(frame);
bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node)); bool fit_to_paper_size = !(PrintingNodeOrPdfFrame(frame, node));
if (!InitPrintSettings(fit_to_paper_size, device_name)) { if (!InitPrintSettings(fit_to_paper_size, device_name)) {
@ -1081,11 +1067,11 @@ bool PrintWebViewHelper::UpdatePrintSettings(
if (!print_for_preview_) { if (!print_for_preview_) {
job_settings->GetInteger(kPreviewRequestID, job_settings->GetInteger(kPreviewRequestID,
&settings.params.preview_request_id); &settings.params.preview_request_id);
settings.params.print_to_pdf = true; settings.params.print_to_pdf = true;
UpdateFrameMarginsCssInfo(*job_settings); UpdateFrameMarginsCssInfo(*job_settings);
settings.params.print_scaling_option = settings.params.print_scaling_option =
blink::kWebPrintScalingOptionSourceSize; blink::kWebPrintScalingOptionSourceSize;
} }
SetPrintPagesParams(settings); SetPrintPagesParams(settings);
@ -1207,11 +1193,9 @@ PrintWebViewHelper::PrintPreviewContext::PrintPreviewContext()
generate_draft_pages_(true), generate_draft_pages_(true),
print_ready_metafile_page_count_(0), print_ready_metafile_page_count_(0),
error_(PREVIEW_ERROR_NONE), error_(PREVIEW_ERROR_NONE),
state_(UNINITIALIZED) { state_(UNINITIALIZED) {}
}
PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() { PrintWebViewHelper::PrintPreviewContext::~PrintPreviewContext() {}
}
void PrintWebViewHelper::PrintPreviewContext::InitWithFrame( void PrintWebViewHelper::PrintPreviewContext::InitWithFrame(
blink::WebLocalFrame* web_frame) { blink::WebLocalFrame* web_frame) {
@ -1391,8 +1375,8 @@ blink::WebLocalFrame* PrintWebViewHelper::PrintPreviewContext::source_frame() {
return source_frame_.GetFrame(); return source_frame_.GetFrame();
} }
const blink::WebNode& const blink::WebNode& PrintWebViewHelper::PrintPreviewContext::source_node()
PrintWebViewHelper::PrintPreviewContext::source_node() const { const {
DCHECK(state_ != UNINITIALIZED); DCHECK(state_ != UNINITIALIZED);
return source_node_; return source_node_;
} }
@ -1403,8 +1387,8 @@ PrintWebViewHelper::PrintPreviewContext::prepared_frame() {
return prep_frame_view_->frame(); return prep_frame_view_->frame();
} }
const blink::WebNode& const blink::WebNode& PrintWebViewHelper::PrintPreviewContext::prepared_node()
PrintWebViewHelper::PrintPreviewContext::prepared_node() const { const {
DCHECK(state_ != UNINITIALIZED); DCHECK(state_ != UNINITIALIZED);
return prep_frame_view_->node(); return prep_frame_view_->node();
} }

View file

@ -38,11 +38,10 @@ bool PrintWebViewHelper::RenderPreviewPage(
} }
base::TimeTicks begin_time = base::TimeTicks::Now(); base::TimeTicks begin_time = base::TimeTicks::Now();
PrintPageInternal(page_params, PrintPageInternal(page_params, print_preview_context_.prepared_frame(),
print_preview_context_.prepared_frame(),
initial_render_metafile); initial_render_metafile);
print_preview_context_.RenderedPreviewPage( print_preview_context_.RenderedPreviewPage(base::TimeTicks::Now() -
base::TimeTicks::Now() - begin_time); begin_time);
if (draft_metafile.get()) { if (draft_metafile.get()) {
draft_metafile->FinishDocument(); draft_metafile->FinishDocument();
} else if (print_preview_context_.IsModifiable() && } else if (print_preview_context_.IsModifiable() &&
@ -51,7 +50,6 @@ bool PrintWebViewHelper::RenderPreviewPage(
draft_metafile = draft_metafile =
print_preview_context_.metafile()->GetMetafileForCurrentPage( print_preview_context_.metafile()->GetMetafileForCurrentPage(
SkiaDocumentType::PDF); SkiaDocumentType::PDF);
} }
return PreviewPageRendered(page_number, draft_metafile.get()); return PreviewPageRendered(page_number, draft_metafile.get());
} }
@ -94,8 +92,8 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebLocalFrame* frame,
metafile.FinishDocument(); metafile.FinishDocument();
PrintHostMsg_DidPrintPage_Params printed_page_params; PrintHostMsg_DidPrintPage_Params printed_page_params;
if (!CopyMetafileDataToSharedMem( if (!CopyMetafileDataToSharedMem(metafile,
metafile, &printed_page_params.metafile_data_handle)) { &printed_page_params.metafile_data_handle)) {
return false; return false;
} }

View file

@ -16,7 +16,6 @@
#include "printing/units.h" #include "printing/units.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
namespace printing { namespace printing {
using blink::WebLocalFrame; using blink::WebLocalFrame;
@ -35,13 +34,10 @@ bool PrintWebViewHelper::RenderPreviewPage(
} }
base::TimeTicks begin_time = base::TimeTicks::Now(); base::TimeTicks begin_time = base::TimeTicks::Now();
PrintPageInternal(page_params, PrintPageInternal(page_params, print_preview_context_.prepared_frame(),
print_preview_context_.prepared_frame(), initial_render_metafile, NULL, NULL);
initial_render_metafile, print_preview_context_.RenderedPreviewPage(base::TimeTicks::Now() -
NULL, begin_time);
NULL);
print_preview_context_.RenderedPreviewPage(
base::TimeTicks::Now() - begin_time);
if (draft_metafile.get()) { if (draft_metafile.get()) {
draft_metafile->FinishDocument(); draft_metafile->FinishDocument();
} else if (print_preview_context_.IsModifiable() && } else if (print_preview_context_.IsModifiable() &&
@ -84,10 +80,7 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebLocalFrame* frame,
page_params.params = params.params; page_params.params = params.params;
for (size_t i = 0; i < printed_pages.size(); ++i) { for (size_t i = 0; i < printed_pages.size(); ++i) {
page_params.page_number = printed_pages[i]; page_params.page_number = printed_pages[i];
PrintPageInternal(page_params, PrintPageInternal(page_params, frame, &metafile, &page_size_in_dpi[i],
frame,
&metafile,
&page_size_in_dpi[i],
&content_area_in_dpi[i]); &content_area_in_dpi[i]);
} }
@ -97,8 +90,8 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebLocalFrame* frame,
metafile.FinishDocument(); metafile.FinishDocument();
PrintHostMsg_DidPrintPage_Params printed_page_params; PrintHostMsg_DidPrintPage_Params printed_page_params;
if (!CopyMetafileDataToSharedMem( if (!CopyMetafileDataToSharedMem(metafile,
metafile, &printed_page_params.metafile_data_handle)) { &printed_page_params.metafile_data_handle)) {
return false; return false;
} }
@ -138,10 +131,10 @@ void PrintWebViewHelper::PrintPageInternal(
// Calculate the actual page size and content area in dpi. // Calculate the actual page size and content area in dpi.
if (page_size_in_dpi) { if (page_size_in_dpi) {
*page_size_in_dpi = *page_size_in_dpi =
gfx::Size(static_cast<int>(ConvertUnitDouble( gfx::Size(static_cast<int>(ConvertUnitDouble(page_size.width(),
page_size.width(), kPointsPerInch, dpi)), kPointsPerInch, dpi)),
static_cast<int>(ConvertUnitDouble( static_cast<int>(ConvertUnitDouble(page_size.height(),
page_size.height(), kPointsPerInch, dpi))); kPointsPerInch, dpi)));
} }
if (content_area_in_dpi) { if (content_area_in_dpi) {
@ -150,8 +143,7 @@ void PrintWebViewHelper::PrintPageInternal(
gfx::Rect(0, 0, page_size_in_dpi->width(), page_size_in_dpi->height()); gfx::Rect(0, 0, page_size_in_dpi->width(), page_size_in_dpi->height());
} }
gfx::Rect canvas_area = gfx::Rect canvas_area = content_area;
content_area;
#if 0 #if 0
params.params.display_header_footer ? gfx::Rect(page_size) : content_area; params.params.display_header_footer ? gfx::Rect(page_size) : content_area;
#endif #endif
@ -180,12 +172,9 @@ void PrintWebViewHelper::PrintPageInternal(
} }
#endif #endif
float webkit_scale_factor = RenderPageContent(frame, float webkit_scale_factor =
params.page_number, RenderPageContent(frame, params.page_number, canvas_area, content_area,
canvas_area, scale_factor, canvas);
content_area,
scale_factor,
canvas);
DCHECK_GT(webkit_scale_factor, 0.0f); DCHECK_GT(webkit_scale_factor, 0.0f);
// Done printing. Close the device context to retrieve the compiled metafile. // Done printing. Close the device context to retrieve the compiled metafile.
if (!metafile->FinishPage()) if (!metafile->FinishPage())

View file

@ -13,12 +13,12 @@
#include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/platform/WebVector.h"
using content::RenderThread;
using blink::WebSpeechSynthesizerClient;
using blink::WebSpeechSynthesisUtterance; using blink::WebSpeechSynthesisUtterance;
using blink::WebSpeechSynthesisVoice; using blink::WebSpeechSynthesisVoice;
using blink::WebSpeechSynthesizerClient;
using blink::WebString; using blink::WebString;
using blink::WebVector; using blink::WebVector;
using content::RenderThread;
int TtsDispatcher::next_utterance_id_ = 1; int TtsDispatcher::next_utterance_id_ = 1;

View file

@ -73,7 +73,8 @@ void PrintingHandlerWin::OnRenderPDFPagesToMetafile(
postscript_level = chrome_pdf::PrintingMode::kPostScript3; postscript_level = chrome_pdf::PrintingMode::kPostScript3;
break; break;
default: default:
postscript_level = chrome_pdf::PrintingMode::kEmf; // Not using postscript. postscript_level =
chrome_pdf::PrintingMode::kEmf; // Not using postscript.
} }
chrome_pdf::SetPDFUsePrintMode(postscript_level); chrome_pdf::SetPDFUsePrintMode(postscript_level);

View file

@ -23,13 +23,12 @@ SizeConstraints::~SizeConstraints() {}
gfx::Size SizeConstraints::AddFrameToConstraints( gfx::Size SizeConstraints::AddFrameToConstraints(
const gfx::Size& size_constraints, const gfx::Size& size_constraints,
const gfx::Insets& frame_insets) { const gfx::Insets& frame_insets) {
return gfx::Size( return gfx::Size(size_constraints.width() == kUnboundedSize
size_constraints.width() == kUnboundedSize ? kUnboundedSize
? kUnboundedSize : size_constraints.width() + frame_insets.width(),
: size_constraints.width() + frame_insets.width(), size_constraints.height() == kUnboundedSize
size_constraints.height() == kUnboundedSize ? kUnboundedSize
? kUnboundedSize : size_constraints.height() + frame_insets.height());
: size_constraints.height() + frame_insets.height());
} }
gfx::Size SizeConstraints::ClampSize(gfx::Size size) const { gfx::Size SizeConstraints::ClampSize(gfx::Size size) const {

View file

@ -28,20 +28,16 @@ namespace {
// TODO(aa): What about more obscure schemes like data: and javascript: ? // TODO(aa): What about more obscure schemes like data: and javascript: ?
// Note: keep this array in sync with kValidSchemeMasks. // Note: keep this array in sync with kValidSchemeMasks.
const char* const kValidSchemes[] = { const char* const kValidSchemes[] = {
url::kHttpScheme, url::kHttpsScheme, url::kHttpScheme, url::kHttpsScheme, url::kFileScheme,
url::kFileScheme, url::kFtpScheme, url::kFtpScheme, content::kChromeUIScheme, kExtensionScheme,
content::kChromeUIScheme, kExtensionScheme,
url::kFileSystemScheme, url::kFileSystemScheme,
}; };
const int kValidSchemeMasks[] = { const int kValidSchemeMasks[] = {
URLPattern::SCHEME_HTTP, URLPattern::SCHEME_HTTP, URLPattern::SCHEME_HTTPS,
URLPattern::SCHEME_HTTPS, URLPattern::SCHEME_FILE, URLPattern::SCHEME_FTP,
URLPattern::SCHEME_FILE, URLPattern::SCHEME_CHROMEUI, URLPattern::SCHEME_EXTENSION,
URLPattern::SCHEME_FTP, URLPattern::SCHEME_FILESYSTEM,
URLPattern::SCHEME_CHROMEUI,
URLPattern::SCHEME_EXTENSION,
URLPattern::SCHEME_FILESYSTEM,
}; };
static_assert(arraysize(kValidSchemes) == arraysize(kValidSchemeMasks), static_assert(arraysize(kValidSchemes) == arraysize(kValidSchemeMasks),
@ -59,15 +55,15 @@ const char kParseErrorInvalidHost[] = "Invalid host.";
// Message explaining each URLPattern::ParseResult. // Message explaining each URLPattern::ParseResult.
const char* const kParseResultMessages[] = { const char* const kParseResultMessages[] = {
kParseSuccess, kParseSuccess,
kParseErrorMissingSchemeSeparator, kParseErrorMissingSchemeSeparator,
kParseErrorInvalidScheme, kParseErrorInvalidScheme,
kParseErrorWrongSchemeType, kParseErrorWrongSchemeType,
kParseErrorEmptyHost, kParseErrorEmptyHost,
kParseErrorInvalidHostWildcard, kParseErrorInvalidHostWildcard,
kParseErrorEmptyPath, kParseErrorEmptyPath,
kParseErrorInvalidPort, kParseErrorInvalidPort,
kParseErrorInvalidHost, kParseErrorInvalidHost,
}; };
static_assert(URLPattern::NUM_PARSE_RESULTS == arraysize(kParseResultMessages), static_assert(URLPattern::NUM_PARSE_RESULTS == arraysize(kParseResultMessages),
@ -157,8 +153,7 @@ URLPattern::URLPattern(int valid_schemes, base::StringPiece pattern)
URLPattern::URLPattern(const URLPattern& other) = default; URLPattern::URLPattern(const URLPattern& other) = default;
URLPattern::~URLPattern() { URLPattern::~URLPattern() {}
}
bool URLPattern::operator<(const URLPattern& other) const { bool URLPattern::operator<(const URLPattern& other) const {
return GetAsString() < other.GetAsString(); return GetAsString() < other.GetAsString();
@ -510,8 +505,8 @@ const std::string& URLPattern::GetAsString() const {
bool standard_scheme = IsStandardScheme(scheme_); bool standard_scheme = IsStandardScheme(scheme_);
std::string spec = scheme_ + std::string spec =
(standard_scheme ? url::kStandardSchemeSeparator : ":"); scheme_ + (standard_scheme ? url::kStandardSchemeSeparator : ":");
if (scheme_ != url::kFileScheme && standard_scheme) { if (scheme_ != url::kFileScheme && standard_scheme) {
if (match_subdomains_) { if (match_subdomains_) {
@ -540,10 +535,11 @@ bool URLPattern::OverlapsWith(const URLPattern& other) const {
if (match_all_urls() || other.match_all_urls()) if (match_all_urls() || other.match_all_urls())
return true; return true;
return (MatchesAnyScheme(other.GetExplicitSchemes()) || return (MatchesAnyScheme(other.GetExplicitSchemes()) ||
other.MatchesAnyScheme(GetExplicitSchemes())) other.MatchesAnyScheme(GetExplicitSchemes())) &&
&& (MatchesHost(other.host()) || other.MatchesHost(host())) (MatchesHost(other.host()) || other.MatchesHost(host())) &&
&& (MatchesPortPattern(other.port()) || other.MatchesPortPattern(port())) (MatchesPortPattern(other.port()) ||
&& (MatchesPath(StripTrailingWildcard(other.path())) || other.MatchesPortPattern(port())) &&
(MatchesPath(StripTrailingWildcard(other.path())) ||
other.MatchesPath(StripTrailingWildcard(path()))); other.MatchesPath(StripTrailingWildcard(path())));
} }

View file

@ -1,5 +1,6 @@
// This is generated file. Do not modify directly. // This is generated file. Do not modify directly.
// Path to the code generator: tools/generate_library_loader/generate_library_loader.py . // Path to the code generator:
// tools/generate_library_loader/generate_library_loader.py .
#include "library_loaders/libspeechd.h" #include "library_loaders/libspeechd.h"
@ -7,15 +8,20 @@
// Put these sanity checks here so that they fire at most once // Put these sanity checks here so that they fire at most once
// (to avoid cluttering the build output). // (to avoid cluttering the build output).
#if !defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) && !defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if !defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) && \
!defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
#error neither LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN nor LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED defined #error neither LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN nor LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED defined
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) && defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) && \
defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
#error both LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN and LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED defined #error both LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN and LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED defined
#endif #endif
LibSpeechdLoader::LibSpeechdLoader() : loaded_(false) { LibSpeechdLoader::LibSpeechdLoader() : loaded_(false) {}
}
LibSpeechdLoader::~LibSpeechdLoader() { LibSpeechdLoader::~LibSpeechdLoader() {
CleanUp(loaded_); CleanUp(loaded_);
@ -31,13 +37,12 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
return false; return false;
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_open = spd_open =
reinterpret_cast<decltype(this->spd_open)>( reinterpret_cast<decltype(this->spd_open)>(dlsym(library_, "spd_open"));
dlsym(library_, "spd_open"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_open = &::spd_open; spd_open = &::spd_open;
#endif #endif
if (!spd_open) { if (!spd_open) {
@ -47,10 +52,10 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_say = spd_say =
reinterpret_cast<decltype(this->spd_say)>( reinterpret_cast<decltype(this->spd_say)>(dlsym(library_, "spd_say"));
dlsym(library_, "spd_say"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_say = &::spd_say; spd_say = &::spd_say;
#endif #endif
if (!spd_say) { if (!spd_say) {
@ -60,10 +65,10 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_stop = spd_stop =
reinterpret_cast<decltype(this->spd_stop)>( reinterpret_cast<decltype(this->spd_stop)>(dlsym(library_, "spd_stop"));
dlsym(library_, "spd_stop"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_stop = &::spd_stop; spd_stop = &::spd_stop;
#endif #endif
if (!spd_stop) { if (!spd_stop) {
@ -73,10 +78,10 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_close = spd_close =
reinterpret_cast<decltype(this->spd_close)>( reinterpret_cast<decltype(this->spd_close)>(dlsym(library_, "spd_close"));
dlsym(library_, "spd_close"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_close = &::spd_close; spd_close = &::spd_close;
#endif #endif
if (!spd_close) { if (!spd_close) {
@ -86,10 +91,10 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_pause = spd_pause =
reinterpret_cast<decltype(this->spd_pause)>( reinterpret_cast<decltype(this->spd_pause)>(dlsym(library_, "spd_pause"));
dlsym(library_, "spd_pause"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_pause = &::spd_pause; spd_pause = &::spd_pause;
#endif #endif
if (!spd_pause) { if (!spd_pause) {
@ -98,11 +103,11 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
} }
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_resume = spd_resume = reinterpret_cast<decltype(this->spd_resume)>(
reinterpret_cast<decltype(this->spd_resume)>( dlsym(library_, "spd_resume"));
dlsym(library_, "spd_resume"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_resume = &::spd_resume; spd_resume = &::spd_resume;
#endif #endif
if (!spd_resume) { if (!spd_resume) {
@ -115,7 +120,8 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
reinterpret_cast<decltype(this->spd_set_notification_on)>( reinterpret_cast<decltype(this->spd_set_notification_on)>(
dlsym(library_, "spd_set_notification_on")); dlsym(library_, "spd_set_notification_on"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_notification_on = &::spd_set_notification_on; spd_set_notification_on = &::spd_set_notification_on;
#endif #endif
if (!spd_set_notification_on) { if (!spd_set_notification_on) {
@ -124,11 +130,11 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
} }
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_set_voice_rate = spd_set_voice_rate = reinterpret_cast<decltype(this->spd_set_voice_rate)>(
reinterpret_cast<decltype(this->spd_set_voice_rate)>( dlsym(library_, "spd_set_voice_rate"));
dlsym(library_, "spd_set_voice_rate"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_voice_rate = &::spd_set_voice_rate; spd_set_voice_rate = &::spd_set_voice_rate;
#endif #endif
if (!spd_set_voice_rate) { if (!spd_set_voice_rate) {
@ -137,11 +143,11 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
} }
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_set_voice_pitch = spd_set_voice_pitch = reinterpret_cast<decltype(this->spd_set_voice_pitch)>(
reinterpret_cast<decltype(this->spd_set_voice_pitch)>( dlsym(library_, "spd_set_voice_pitch"));
dlsym(library_, "spd_set_voice_pitch"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_voice_pitch = &::spd_set_voice_pitch; spd_set_voice_pitch = &::spd_set_voice_pitch;
#endif #endif
if (!spd_set_voice_pitch) { if (!spd_set_voice_pitch) {
@ -154,7 +160,8 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
reinterpret_cast<decltype(this->spd_list_synthesis_voices)>( reinterpret_cast<decltype(this->spd_list_synthesis_voices)>(
dlsym(library_, "spd_list_synthesis_voices")); dlsym(library_, "spd_list_synthesis_voices"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_list_synthesis_voices = &::spd_list_synthesis_voices; spd_list_synthesis_voices = &::spd_list_synthesis_voices;
#endif #endif
if (!spd_list_synthesis_voices) { if (!spd_list_synthesis_voices) {
@ -167,7 +174,8 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
reinterpret_cast<decltype(this->spd_set_synthesis_voice)>( reinterpret_cast<decltype(this->spd_set_synthesis_voice)>(
dlsym(library_, "spd_set_synthesis_voice")); dlsym(library_, "spd_set_synthesis_voice"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_synthesis_voice = &::spd_set_synthesis_voice; spd_set_synthesis_voice = &::spd_set_synthesis_voice;
#endif #endif
if (!spd_set_synthesis_voice) { if (!spd_set_synthesis_voice) {
@ -176,11 +184,11 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
} }
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_list_modules = spd_list_modules = reinterpret_cast<decltype(this->spd_list_modules)>(
reinterpret_cast<decltype(this->spd_list_modules)>( dlsym(library_, "spd_list_modules"));
dlsym(library_, "spd_list_modules"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_list_modules = &::spd_list_modules; spd_list_modules = &::spd_list_modules;
#endif #endif
if (!spd_list_modules) { if (!spd_list_modules) {
@ -193,7 +201,8 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
reinterpret_cast<decltype(this->spd_set_output_module)>( reinterpret_cast<decltype(this->spd_set_output_module)>(
dlsym(library_, "spd_set_output_module")); dlsym(library_, "spd_set_output_module"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_output_module = &::spd_set_output_module; spd_set_output_module = &::spd_set_output_module;
#endif #endif
if (!spd_set_output_module) { if (!spd_set_output_module) {
@ -202,11 +211,11 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
} }
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN) #if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DLOPEN)
spd_set_language = spd_set_language = reinterpret_cast<decltype(this->spd_set_language)>(
reinterpret_cast<decltype(this->spd_set_language)>( dlsym(library_, "spd_set_language"));
dlsym(library_, "spd_set_language"));
#endif #endif
#if defined(LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED) #if defined( \
LIBRARY_LOADER_OUT_RELEASE_GEN_LIBRARY_LOADERS_LIBSPEECHD_H_DT_NEEDED)
spd_set_language = &::spd_set_language; spd_set_language = &::spd_set_language;
#endif #endif
if (!spd_set_language) { if (!spd_set_language) {
@ -214,7 +223,6 @@ bool LibSpeechdLoader::Load(const std::string& library_name) {
return false; return false;
} }
loaded_ = true; loaded_ = true;
return true; return true;
} }
@ -241,5 +249,4 @@ void LibSpeechdLoader::CleanUp(bool unload) {
spd_list_modules = NULL; spd_list_modules = NULL;
spd_set_output_module = NULL; spd_set_output_module = NULL;
spd_set_language = NULL; spd_set_language = NULL;
} }