diff options
author | davemoore@chromium.org <davemoore@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-08-04 20:05:17 +0000 |
---|---|---|
committer | davemoore@chromium.org <davemoore@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2010-08-04 20:05:17 +0000 |
commit | 617fd0d2382bcdd87fca3d9377cb796bb0924882 (patch) | |
tree | 034771fda3eb15093d54bb24970034dd77195d2d /chrome | |
parent | bae3069e31b61b1555f65272ec8973b2f4c56df5 (diff) | |
download | chromium_src-617fd0d2382bcdd87fca3d9377cb796bb0924882.zip chromium_src-617fd0d2382bcdd87fca3d9377cb796bb0924882.tar.gz chromium_src-617fd0d2382bcdd87fca3d9377cb796bb0924882.tar.bz2 |
To effectively test some parts of chrome for cros on the linux desktop, we need a way to start chrome logged in. The login UI requires the WM to display, so I added command line options to do this. But we needed the full functionality of login, which doesn't work when libcros can't be loaded. I created stubs for all the cros api. I then took both stubs and the real implementations and put them entirely inside the .cc files (no separate declaration of the implementations in the .h files).
Review URL: http://codereview.chromium.org/3076029
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@54950 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome')
33 files changed, 2324 insertions, 2213 deletions
diff --git a/chrome/browser/browser_init.cc b/chrome/browser/browser_init.cc index 237ff95..dd79815 100644 --- a/chrome/browser/browser_init.cc +++ b/chrome/browser/browser_init.cc @@ -1038,8 +1038,10 @@ bool BrowserInit::ProcessCmdLineImpl(const CommandLine& command_line, #if defined(OS_CHROMEOS) // The browser will be launched after the user logs in. - if (command_line.HasSwitch(switches::kLoginManager)) + if (command_line.HasSwitch(switches::kLoginManager) || + command_line.HasSwitch(switches::kLoginPassword)) { silent_launch = true; + } #endif // If we don't want to launch a new browser window or tab (in the case diff --git a/chrome/browser/browser_main.cc b/chrome/browser/browser_main.cc index d7b50f0..60fab61 100644 --- a/chrome/browser/browser_main.cc +++ b/chrome/browser/browser_main.cc @@ -145,6 +145,8 @@ #include "chrome/browser/chromeos/cros/screen_lock_library.h" #include "chrome/browser/chromeos/customization_document.h" #include "chrome/browser/chromeos/external_metrics.h" +#include "chrome/browser/chromeos/login/authenticator.h" +#include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/screen_locker.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/views/browser_dialogs.h" @@ -681,6 +683,34 @@ void InitializeToolkit() { #if defined(OS_CHROMEOS) +// Class is used to login using passed username and password. +// The instance will be deleted upon success or failure. +class StubLogin : public chromeos::LoginStatusConsumer { + public: + explicit StubLogin(std::string username, std::string password) { + authenticator_ = chromeos::LoginUtils::Get()->CreateAuthenticator(this); + authenticator_.get()->AuthenticateToLogin( + g_browser_process->profile_manager()->GetDefaultProfile(), + username, + password, + std::string(), + std::string()); + } + + void OnLoginFailure(const std::string& error) { + LOG(ERROR) << "Login Failure: " << error; + delete this; + } + + void OnLoginSuccess(const std::string& username, + const GaiaAuthConsumer::ClientLoginResult& credentials) { + chromeos::LoginUtils::Get()->CompleteLogin(username, credentials); + delete this; + } + + scoped_refptr<chromeos::Authenticator> authenticator_; +}; + void OptionallyRunChromeOSLoginManager(const CommandLine& parsed_command_line) { if (parsed_command_line.HasSwitch(switches::kLoginManager)) { std::string first_screen = @@ -702,6 +732,11 @@ void OptionallyRunChromeOSLoginManager(const CommandLine& parsed_command_line) { } } browser::ShowLoginWizard(first_screen, size); + } else if (parsed_command_line.HasSwitch(switches::kLoginUser) && + parsed_command_line.HasSwitch(switches::kLoginPassword)) { + new StubLogin( + parsed_command_line.GetSwitchValueASCII(switches::kLoginUser), + parsed_command_line.GetSwitchValueASCII(switches::kLoginPassword)); } } @@ -722,6 +757,12 @@ OSStatus KeychainCallback(SecKeychainEvent keychain_event, } // namespace +#if defined(OS_CHROMEOS) +// Allows authenticator to be invoked without adding refcounting. The instances +// will delete themselves upon completion. +DISABLE_RUNNABLE_METHOD_REFCOUNT(StubLogin); +#endif + #if defined(OS_WIN) #define DLLEXPORT __declspec(dllexport) @@ -1023,6 +1064,10 @@ int BrowserMain(const MainFunctionParams& parameters) { // Profile creation ---------------------------------------------------------- #if defined(OS_CHROMEOS) + // Stub out chromeos implementations. + if (parsed_command_line.HasSwitch(switches::kStubCros)) + chromeos::CrosLibrary::Get()->GetTestApi()->SetUseStubImpl(); + // Initialize the screen locker now so that it can receive // LOGIN_USER_CHANGED notification from UserManager. chromeos::ScreenLocker::InitClass(); diff --git a/chrome/browser/chromeos/cros/cros_library.cc b/chrome/browser/chromeos/cros/cros_library.cc index a9e469d..d31e76e 100644 --- a/chrome/browser/chromeos/cros/cros_library.cc +++ b/chrome/browser/chromeos/cros/cros_library.cc @@ -22,69 +22,14 @@ namespace chromeos { CrosLibrary::CrosLibrary() : library_loader_(NULL), - crypto_lib_(NULL), - keyboard_lib_(NULL), - input_method_lib_(NULL), - login_lib_(NULL), - mount_lib_(NULL), - network_lib_(NULL), - power_lib_(NULL), - screen_lock_lib_(NULL), - speech_synthesis_lib_(NULL), - synaptics_lib_(NULL), - syslogs_lib_(NULL), - system_lib_(NULL), - update_lib_(NULL), - own_library_loader_(true), - own_cryptohome_lib_(true), - own_keyboard_lib_(true), - own_input_method_lib_(true), - own_login_lib_(true), - own_mount_lib_(true), - own_network_lib_(true), - own_power_lib_(true), - own_screen_lock_lib_(true), - own_speech_synthesis_lib_(true), - own_synaptics_lib_(true), - own_syslogs_lib_(true), - own_system_lib_(true), - own_update_lib_(true), loaded_(false), load_error_(false), test_api_(NULL) { - } CrosLibrary::~CrosLibrary() { if (own_library_loader_) delete library_loader_; - if (own_cryptohome_lib_) - delete crypto_lib_; - if (own_keyboard_lib_) - delete keyboard_lib_; - if (own_input_method_lib_) - delete input_method_lib_; - if (own_login_lib_) - delete login_lib_; - if (own_mount_lib_) - delete mount_lib_; - if (own_network_lib_) - delete network_lib_; - if (own_power_lib_) - delete power_lib_; - if (own_screen_lock_lib_) - delete screen_lock_lib_; - if (own_speech_synthesis_lib_) - delete speech_synthesis_lib_; - if (own_synaptics_lib_) - delete synaptics_lib_; - if (own_syslogs_lib_) - delete syslogs_lib_; - if (own_system_lib_) - delete system_lib_; - if (own_update_lib_) - delete update_lib_; - delete test_api_; } // static @@ -93,84 +38,61 @@ CrosLibrary* CrosLibrary::Get() { } CryptohomeLibrary* CrosLibrary::GetCryptohomeLibrary() { - if (!crypto_lib_) - crypto_lib_ = new CryptohomeLibraryImpl(); - return crypto_lib_; + return crypto_lib_.GetDefaultImpl(use_stub_impl_); } KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() { - if (!keyboard_lib_) - keyboard_lib_ = new KeyboardLibraryImpl(); - return keyboard_lib_; + return keyboard_lib_.GetDefaultImpl(use_stub_impl_); } InputMethodLibrary* CrosLibrary::GetInputMethodLibrary() { - if (!input_method_lib_) - input_method_lib_ = new InputMethodLibraryImpl(); - return input_method_lib_; + return input_method_lib_.GetDefaultImpl(use_stub_impl_); } LoginLibrary* CrosLibrary::GetLoginLibrary() { - if (!login_lib_) - login_lib_ = new LoginLibraryImpl(); - return login_lib_; + return login_lib_.GetDefaultImpl(use_stub_impl_); } MountLibrary* CrosLibrary::GetMountLibrary() { - if (!mount_lib_) - mount_lib_ = new MountLibraryImpl(); - return mount_lib_; + return mount_lib_.GetDefaultImpl(use_stub_impl_); } NetworkLibrary* CrosLibrary::GetNetworkLibrary() { - if (!network_lib_) - network_lib_ = new NetworkLibraryImpl(); - return network_lib_; + return network_lib_.GetDefaultImpl(use_stub_impl_); } PowerLibrary* CrosLibrary::GetPowerLibrary() { - if (!power_lib_) - power_lib_ = new PowerLibraryImpl(); - return power_lib_; + return power_lib_.GetDefaultImpl(use_stub_impl_); } ScreenLockLibrary* CrosLibrary::GetScreenLockLibrary() { - if (!screen_lock_lib_) - screen_lock_lib_ = new ScreenLockLibraryImpl(); - return screen_lock_lib_; + return screen_lock_lib_.GetDefaultImpl(use_stub_impl_); } SpeechSynthesisLibrary* CrosLibrary::GetSpeechSynthesisLibrary() { - if (!speech_synthesis_lib_) - speech_synthesis_lib_ = new SpeechSynthesisLibraryImpl(); - return speech_synthesis_lib_; + return speech_synthesis_lib_.GetDefaultImpl(use_stub_impl_); } SynapticsLibrary* CrosLibrary::GetSynapticsLibrary() { - if (!synaptics_lib_) - synaptics_lib_ = new SynapticsLibraryImpl(); - return synaptics_lib_; + return synaptics_lib_.GetDefaultImpl(use_stub_impl_); } SyslogsLibrary* CrosLibrary::GetSyslogsLibrary() { - if (!syslogs_lib_) - syslogs_lib_ = new SyslogsLibraryImpl(); - return syslogs_lib_; + return syslogs_lib_.GetDefaultImpl(use_stub_impl_); } SystemLibrary* CrosLibrary::GetSystemLibrary() { - if (!system_lib_) - system_lib_ = new SystemLibraryImpl(); - return system_lib_; + return system_lib_.GetDefaultImpl(use_stub_impl_); } UpdateLibrary* CrosLibrary::GetUpdateLibrary() { - if (!update_lib_) - update_lib_ = new UpdateLibraryImpl(); - return update_lib_; + return update_lib_.GetDefaultImpl(use_stub_impl_); } bool CrosLibrary::EnsureLoaded() { + if (use_stub_impl_) + return true; + if (!loaded_ && !load_error_) { if (!library_loader_) library_loader_ = new CrosLibraryLoader(); @@ -186,6 +108,10 @@ CrosLibrary::TestApi* CrosLibrary::GetTestApi() { return test_api_; } +void CrosLibrary::TestApi::SetUseStubImpl() { + library_->use_stub_impl_ = true; +} + void CrosLibrary::TestApi::SetLibraryLoader(LibraryLoader* loader, bool own) { if (library_->library_loader_ == loader) return; @@ -199,105 +125,69 @@ void CrosLibrary::TestApi::SetLibraryLoader(LibraryLoader* loader, bool own) { library_->load_error_ = false; } -void CrosLibrary::TestApi::SetCryptohomeLibrary(CryptohomeLibrary* library, - bool own) { - if (library_->own_cryptohome_lib_) - delete library_->crypto_lib_; - library_->own_cryptohome_lib_ = own; - library_->crypto_lib_ = library; +void CrosLibrary::TestApi::SetCryptohomeLibrary( + CryptohomeLibrary* library, bool own) { + library_->crypto_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetKeyboardLibrary(KeyboardLibrary* library, - bool own) { - if (library_->own_keyboard_lib_) - delete library_->keyboard_lib_; - library_->own_keyboard_lib_ = own; - library_->keyboard_lib_ = library; +void CrosLibrary::TestApi::SetKeyboardLibrary( + KeyboardLibrary* library, bool own) { + library_->keyboard_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetInputMethodLibrary(InputMethodLibrary* library, - bool own) { - if (library_->own_input_method_lib_) - delete library_->input_method_lib_; - library_->own_input_method_lib_ = own; - library_->input_method_lib_ = library; +void CrosLibrary::TestApi::SetInputMethodLibrary( + InputMethodLibrary* library, bool own) { + library_->input_method_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetLoginLibrary(LoginLibrary* library, bool own) { - if (library_->own_login_lib_) - delete library_->login_lib_; - library_->own_login_lib_ = own; - library_->login_lib_ = library; +void CrosLibrary::TestApi::SetLoginLibrary( + LoginLibrary* library, bool own) { + library_->login_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetMountLibrary(MountLibrary* library, bool own) { - if (library_->own_mount_lib_) - delete library_->mount_lib_; - library_->own_mount_lib_ = own; - library_->mount_lib_ = library; +void CrosLibrary::TestApi::SetMountLibrary( + MountLibrary* library, bool own) { + library_->mount_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetNetworkLibrary(NetworkLibrary* library, - bool own) { - if (library_->own_network_lib_) - delete library_->network_lib_; - library_->own_network_lib_ = own; - library_->network_lib_ = library; +void CrosLibrary::TestApi::SetNetworkLibrary( + NetworkLibrary* library, bool own) { + library_->network_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetPowerLibrary(PowerLibrary* library, bool own) { - if (library_->own_power_lib_) - delete library_->power_lib_; - library_->own_power_lib_ = own; - library_->power_lib_ = library; +void CrosLibrary::TestApi::SetPowerLibrary( + PowerLibrary* library, bool own) { + library_->power_lib_.SetImpl(library, own); } -void CrosLibrary::TestApi::SetScreenLockLibrary(ScreenLockLibrary* library, - bool own) { - if (library_->own_screen_lock_lib_) - delete library_->screen_lock_lib_; - library_->own_screen_lock_lib_ = own; - library_->screen_lock_lib_ = library; +void CrosLibrary::TestApi::SetScreenLockLibrary( + ScreenLockLibrary* library, bool own) { + library_->screen_lock_lib_.SetImpl(library, own); } void CrosLibrary::TestApi::SetSpeechSynthesisLibrary( SpeechSynthesisLibrary* library, bool own) { - if (library_->own_speech_synthesis_lib_) - delete library_->speech_synthesis_lib_; - library_->own_speech_synthesis_lib_ = own; - library_->speech_synthesis_lib_ = library; -} - -void CrosLibrary::TestApi::SetSynapticsLibrary(SynapticsLibrary* library, - bool own) { - if (library_->own_synaptics_lib_) - delete library_->synaptics_lib_; - library_->own_synaptics_lib_ = own; - library_->synaptics_lib_ = library; -} - -void CrosLibrary::TestApi::SetSyslogsLibrary(SyslogsLibrary* library, - bool own) { - if (library_->syslogs_lib_) - delete library_->syslogs_lib_; - library_->own_syslogs_lib_ = own; - library_->syslogs_lib_ = library; -} - -void CrosLibrary::TestApi::SetSystemLibrary(SystemLibrary* library, - bool own) { - if (library_->system_lib_) - delete library_->system_lib_; - library_->own_system_lib_ = own; - library_->system_lib_ = library; -} - -void CrosLibrary::TestApi::SetUpdateLibrary(UpdateLibrary* library, - bool own) { - if (library_->update_lib_) - delete library_->update_lib_; - library_->own_update_lib_ = own; - library_->update_lib_ = library; + library_->speech_synthesis_lib_.SetImpl(library, own); +} + +void CrosLibrary::TestApi::SetSynapticsLibrary( + SynapticsLibrary* library, bool own) { + library_->synaptics_lib_.SetImpl(library, own); +} + +void CrosLibrary::TestApi::SetSyslogsLibrary( + SyslogsLibrary* library, bool own) { + library_->syslogs_lib_.SetImpl(library, own); +} + +void CrosLibrary::TestApi::SetSystemLibrary( + SystemLibrary* library, bool own) { + library_->system_lib_.SetImpl(library, own); +} + +void CrosLibrary::TestApi::SetUpdateLibrary( + UpdateLibrary* library, bool own) { + library_->update_lib_.SetImpl(library, own); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/cros_library.h b/chrome/browser/chromeos/cros/cros_library.h index 76650ab..3f3b7b5 100644 --- a/chrome/browser/chromeos/cros/cros_library.h +++ b/chrome/browser/chromeos/cros/cros_library.h @@ -9,7 +9,6 @@ #include <string> #include "base/basictypes.h" #include "base/singleton.h" - namespace chromeos { class CryptohomeLibrary; @@ -32,12 +31,14 @@ class UpdateLibrary; // be mocked for testing. class CrosLibrary { public: - // This class provides access to internal members of CrosLibrary class for // purpose of testing (i.e. replacement of members' implementation with // mock objects). class TestApi { public: + // Use the stub implementations of the library. This is mainly for + // running the chromeos build of chrome on the desktop. + void SetUseStubImpl(); // Passing true for own for these setters will cause them to be deleted // when the CrosLibrary is deleted (or other mocks are set). // Setter for LibraryLoader. @@ -137,35 +138,58 @@ class CrosLibrary { virtual ~CrosLibrary(); LibraryLoader* library_loader_; - CryptohomeLibrary* crypto_lib_; - KeyboardLibrary* keyboard_lib_; - InputMethodLibrary* input_method_lib_; - LoginLibrary* login_lib_; - MountLibrary* mount_lib_; - NetworkLibrary* network_lib_; - PowerLibrary* power_lib_; - ScreenLockLibrary* screen_lock_lib_; - SpeechSynthesisLibrary* speech_synthesis_lib_; - SynapticsLibrary* synaptics_lib_; - SyslogsLibrary* syslogs_lib_; - SystemLibrary* system_lib_; - UpdateLibrary* update_lib_; - bool own_library_loader_; - bool own_cryptohome_lib_; - bool own_keyboard_lib_; - bool own_input_method_lib_; - bool own_login_lib_; - bool own_mount_lib_; - bool own_network_lib_; - bool own_power_lib_; - bool own_screen_lock_lib_; - bool own_speech_synthesis_lib_; - bool own_synaptics_lib_; - bool own_syslogs_lib_; - bool own_system_lib_; - bool own_update_lib_; + // This template supports the creation, setting and optional deletion of + // the cros libraries. + template <class L> + class Library { + public: + Library() : library_(NULL), own_(true) {} + + ~Library() { + if (own_) + delete library_; + } + + L* GetDefaultImpl(bool use_stub_impl) { + if (!library_) { + own_ = true; + library_ = L::GetImpl(use_stub_impl); + } + return library_; + } + + void SetImpl(L* library, bool own) { + if (library != library_) { + if (own_) + delete library_; + library_ = library; + own_ = own; + } + } + + private: + L* library_; + bool own_; + }; + + Library<CryptohomeLibrary> crypto_lib_; + Library<KeyboardLibrary> keyboard_lib_; + Library<InputMethodLibrary> input_method_lib_; + Library<LoginLibrary> login_lib_; + Library<MountLibrary> mount_lib_; + Library<NetworkLibrary> network_lib_; + Library<PowerLibrary> power_lib_; + Library<ScreenLockLibrary> screen_lock_lib_; + Library<SpeechSynthesisLibrary> speech_synthesis_lib_; + Library<SynapticsLibrary> synaptics_lib_; + Library<SyslogsLibrary> syslogs_lib_; + Library<SystemLibrary> system_lib_; + Library<UpdateLibrary> update_lib_; + + // Stub implementations of the libraries should be used. + bool use_stub_impl_; // True if libcros was successfully loaded. bool loaded_; // True if the last load attempt had an error. diff --git a/chrome/browser/chromeos/cros/cryptohome_library.cc b/chrome/browser/chromeos/cros/cryptohome_library.cc index 6ac8432..dcdf456 100644 --- a/chrome/browser/chromeos/cros/cryptohome_library.cc +++ b/chrome/browser/chromeos/cros/cryptohome_library.cc @@ -9,41 +9,100 @@ namespace chromeos { -bool CryptohomeLibraryImpl::CheckKey(const std::string& user_email, - const std::string& passhash) { - return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str()); -} +// This class handles the interaction with the ChromeOS cryptohome library APIs. +class CryptohomeLibraryImpl: public CryptohomeLibrary { + public: + CryptohomeLibraryImpl() {} + virtual ~CryptohomeLibraryImpl() {} -bool CryptohomeLibraryImpl::MigrateKey(const std::string& user_email, - const std::string& old_hash, - const std::string& new_hash) { - return chromeos::CryptohomeMigrateKey(user_email.c_str(), - old_hash.c_str(), - new_hash.c_str()); -} + bool CheckKey(const std::string& user_email, const std::string& passhash) { + return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str()); + } -bool CryptohomeLibraryImpl::Remove(const std::string& user_email) { - return chromeos::CryptohomeRemove(user_email.c_str()); -} + bool MigrateKey(const std::string& user_email, + const std::string& old_hash, + const std::string& new_hash) { + return chromeos::CryptohomeMigrateKey(user_email.c_str(), old_hash.c_str(), + new_hash.c_str()); + } -bool CryptohomeLibraryImpl::Mount(const std::string& user_email, - const std::string& passhash, - int* error_code) { - return chromeos::CryptohomeMountAllowFail(user_email.c_str(), - passhash.c_str(), - error_code); -} + bool Remove(const std::string& user_email) { + return chromeos::CryptohomeRemove(user_email.c_str()); + } -bool CryptohomeLibraryImpl::MountForBwsi(int* error_code) { - return chromeos::CryptohomeMountGuest(error_code); -} + bool Mount(const std::string& user_email, + const std::string& passhash, + int* error_code) { + return chromeos::CryptohomeMountAllowFail(user_email.c_str(), + passhash.c_str(), error_code); + } -bool CryptohomeLibraryImpl::IsMounted() { - return chromeos::CryptohomeIsMounted(); -} + bool MountForBwsi(int* error_code) { + return chromeos::CryptohomeMountGuest(error_code); + } + + bool IsMounted() { + return chromeos::CryptohomeIsMounted(); + } + + CryptohomeBlob GetSystemSalt() { + return chromeos::CryptohomeGetSystemSalt(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl); +}; + +class CryptohomeLibraryStubImpl: public CryptohomeLibrary { + public: + CryptohomeLibraryStubImpl() {} + virtual ~CryptohomeLibraryStubImpl() {} + + bool CheckKey(const std::string& user_email, const std::string& passhash) { + return true; + } + + bool MigrateKey(const std::string& user_email, + const std::string& old_hash, + const std::string& new_hash) { + return true; + } + + bool Remove(const std::string& user_email) { + return true; + } + + bool Mount(const std::string& user_email, + const std::string& passhash, + int* error_code) { + return true; + } + + bool MountForBwsi(int* error_code) { + return true; + } + + bool IsMounted() { + return true; + } + + CryptohomeBlob GetSystemSalt() { + CryptohomeBlob salt = CryptohomeBlob(); + salt.push_back(0); + salt.push_back(0); + return salt; + } + + private: + DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl); +}; -CryptohomeBlob CryptohomeLibraryImpl::GetSystemSalt() { - return chromeos::CryptohomeGetSystemSalt(); +// static +CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) { + if (stub) + return new CryptohomeLibraryStubImpl(); + else + return new CryptohomeLibraryImpl(); } -} // namespace chromeos +} // namespace chromeos diff --git a/chrome/browser/chromeos/cros/cryptohome_library.h b/chrome/browser/chromeos/cros/cryptohome_library.h index ea2a809..cee7063 100644 --- a/chrome/browser/chromeos/cros/cryptohome_library.h +++ b/chrome/browser/chromeos/cros/cryptohome_library.h @@ -49,36 +49,8 @@ class CryptohomeLibrary { // Asks cryptohomed for the system salt. virtual CryptohomeBlob GetSystemSalt() = 0; -}; - -// This class handles the interaction with the ChromeOS cryptohome library APIs. -class CryptohomeLibraryImpl : public CryptohomeLibrary { - public: - CryptohomeLibraryImpl() {} - virtual ~CryptohomeLibraryImpl() {} - - // CryptohomeLibrary overrides. - virtual bool Mount(const std::string& user_email, - const std::string& passhash, - int* error_code); - - virtual bool MountForBwsi(int* error_code); - - virtual bool CheckKey(const std::string& user_email, - const std::string& passhash); - - virtual bool MigrateKey(const std::string& user_email, - const std::string& old_hash, - const std::string& new_hash); - - virtual bool Remove(const std::string& user_email); - - virtual bool IsMounted(); - - virtual CryptohomeBlob GetSystemSalt(); - - private: - DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl); + // Get library implementation. + static CryptohomeLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/input_method_library.cc b/chrome/browser/chromeos/cros/input_method_library.cc index 29818e9..4e17374 100644 --- a/chrome/browser/chromeos/cros/input_method_library.cc +++ b/chrome/browser/chromeos/cros/input_method_library.cc @@ -16,10 +16,6 @@ #include <glib.h> #include <signal.h> -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::InputMethodLibraryImpl); - namespace { // Finds a property which has |new_prop.key| from |prop_list|, and replaces the @@ -47,412 +43,562 @@ const char kDefaultKeyboardLayout[] = "us"; namespace chromeos { -InputMethodLibraryImpl::InputMethodLibraryImpl() - : input_method_status_connection_(NULL), - previous_input_method_("", "", "", ""), - current_input_method_("", "", "", ""), - ime_running_(false), - ime_connected_(false), - defer_ime_startup_(false), - active_input_method_(kHardwareKeyboardLayout), - need_input_method_set_(false), - ime_handle_(0), - candidate_window_handle_(0) { - scoped_ptr<InputMethodDescriptors> input_method_descriptors( - CreateFallbackInputMethodDescriptors()); - current_input_method_ = input_method_descriptors->at(0); -} - -InputMethodLibraryImpl::~InputMethodLibraryImpl() { - StopInputMethodProcesses(); -} +// This class handles the interaction with the ChromeOS language library APIs. +// Classes can add themselves as observers. Users can get an instance of this +// library class like this: InputMethodLibrary::Get() +class InputMethodLibraryImpl : public InputMethodLibrary { + public: + InputMethodLibraryImpl() + : input_method_status_connection_(NULL), + previous_input_method_("", "", "", ""), + current_input_method_("", "", "", ""), + ime_running_(false), + ime_connected_(false), + defer_ime_startup_(false), + active_input_method_(kHardwareKeyboardLayout), + need_input_method_set_(false), + ime_handle_(0), + candidate_window_handle_(0) { + scoped_ptr<InputMethodDescriptors> input_method_descriptors( + CreateFallbackInputMethodDescriptors()); + current_input_method_ = input_method_descriptors->at(0); + } -InputMethodLibraryImpl::Observer::~Observer() { -} + ~InputMethodLibraryImpl() { + StopInputMethodProcesses(); + } -void InputMethodLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void InputMethodLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -chromeos::InputMethodDescriptors* -InputMethodLibraryImpl::GetActiveInputMethods() { - chromeos::InputMethodDescriptors* result = NULL; - // The connection does not need to be alive, but it does need to be created. - if (EnsureLoadedAndStarted()) { - result = chromeos::GetActiveInputMethods(input_method_status_connection_); + InputMethodDescriptors* GetActiveInputMethods() { + chromeos::InputMethodDescriptors* result = NULL; + // The connection does not need to be alive, but it does need to be created. + if (EnsureLoadedAndStarted()) { + result = chromeos::GetActiveInputMethods(input_method_status_connection_); + } + if (!result || result->empty()) { + result = CreateFallbackInputMethodDescriptors(); + } + return result; } - if (!result || result->empty()) { - result = CreateFallbackInputMethodDescriptors(); + + size_t GetNumActiveInputMethods() { + scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); + return input_methods->size(); } - return result; -} -size_t InputMethodLibraryImpl::GetNumActiveInputMethods() { - scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); - return input_methods->size(); -} + InputMethodDescriptors* GetSupportedInputMethods() { + InputMethodDescriptors* result = NULL; + // The connection does not need to be alive, but it does need to be created. + if (EnsureLoadedAndStarted()) { + result = chromeos::GetSupportedInputMethods( + input_method_status_connection_); + } + if (!result || result->empty()) { + result = CreateFallbackInputMethodDescriptors(); + } + return result; + } -chromeos::InputMethodDescriptors* -InputMethodLibraryImpl::GetSupportedInputMethods() { - chromeos::InputMethodDescriptors* result = NULL; - // The connection does not need to be alive, but it does need to be created. - if (EnsureLoadedAndStarted()) { - result = chromeos::GetSupportedInputMethods( - input_method_status_connection_); + void ChangeInputMethod(const std::string& input_method_id) { + if (EnsureLoadedAndStarted()) { + if (input_method_id != kHardwareKeyboardLayout) { + StartInputMethodProcesses(); + } + chromeos::ChangeInputMethod( + input_method_status_connection_, input_method_id.c_str()); + } } - if (!result || result->empty()) { - result = CreateFallbackInputMethodDescriptors(); + + void SetImePropertyActivated(const std::string& key, + bool activated) { + DCHECK(!key.empty()); + if (EnsureLoadedAndStarted()) { + chromeos::SetImePropertyActivated( + input_method_status_connection_, key.c_str(), activated); + } } - return result; -} -void InputMethodLibraryImpl::ChangeInputMethod( - const std::string& input_method_id) { - active_input_method_ = input_method_id; - if (EnsureLoadedAndStarted()) { - if (input_method_id != kHardwareKeyboardLayout) { - StartInputMethodProcesses(); + bool InputMethodIsActivated( + const std::string& input_method_id) { + scoped_ptr<InputMethodDescriptors> active_input_method_descriptors( + CrosLibrary::Get()->GetInputMethodLibrary()->GetActiveInputMethods()); + for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) { + if (active_input_method_descriptors->at(i).id == input_method_id) { + return true; + } } - chromeos::ChangeInputMethod( - input_method_status_connection_, input_method_id.c_str()); + return false; } -} -void InputMethodLibraryImpl::SetImePropertyActivated(const std::string& key, - bool activated) { - DCHECK(!key.empty()); - if (EnsureLoadedAndStarted()) { - chromeos::SetImePropertyActivated( - input_method_status_connection_, key.c_str(), activated); + bool GetImeConfig( + const char* section, + const char* config_name, + ImeConfigValue* out_value) { + bool success = false; + if (EnsureLoadedAndStarted()) { + success = chromeos::GetImeConfig( + input_method_status_connection_, section, config_name, out_value); + } + return success; } -} -bool InputMethodLibraryImpl::InputMethodIsActivated( - const std::string& input_method_id) { - scoped_ptr<InputMethodDescriptors> active_input_method_descriptors( - CrosLibrary::Get()->GetInputMethodLibrary()->GetActiveInputMethods()); - for (size_t i = 0; i < active_input_method_descriptors->size(); ++i) { - if (active_input_method_descriptors->at(i).id == input_method_id) { - return true; + bool SetImeConfig( + const char* section, + const char* config_name, + const ImeConfigValue& value) { + MaybeUpdateImeState(section, config_name, value); + + const ConfigKeyType key = std::make_pair(section, config_name); + current_config_values_[key] = value; + if (ime_connected_) { + pending_config_requests_[key] = value; + FlushImeConfig(); } + return pending_config_requests_.empty(); } - return false; -} -bool InputMethodLibraryImpl::GetImeConfig( - const char* section, const char* config_name, ImeConfigValue* out_value) { - bool success = false; - if (EnsureLoadedAndStarted()) { - success = chromeos::GetImeConfig( - input_method_status_connection_, section, config_name, out_value); + virtual const InputMethodDescriptor& previous_input_method() const { + return previous_input_method_; + } + virtual const InputMethodDescriptor& current_input_method() const { + return current_input_method_; } - return success; -} -bool InputMethodLibraryImpl::SetImeConfig( - const char* section, const char* config_name, const ImeConfigValue& value) { - MaybeUpdateImeState(section, config_name, value); + virtual const ImePropertyList& current_ime_properties() const { + return current_ime_properties_; + } - const ConfigKeyType key = std::make_pair(section, config_name); - current_config_values_[key] = value; - if (ime_connected_) { - pending_config_requests_[key] = value; - FlushImeConfig(); + void StartIme() { + ime_running_ = true; + MaybeLaunchIme(); } - return pending_config_requests_.empty(); -} -void InputMethodLibraryImpl::MaybeUpdateImeState( - const char* section, const char* config_name, const ImeConfigValue& value) { - if (!strcmp(kGeneralSectionName, section) && - !strcmp(kPreloadEnginesConfigName, config_name)) { - if (EnsureLoadedAndStarted()) { - if (value.type == ImeConfigValue::kValueTypeStringList && - value.string_list_value.size() == 1 && - value.string_list_value[0] == kHardwareKeyboardLayout) { - StopInputMethodProcesses(); - } else if (!defer_ime_startup_) { - StartInputMethodProcesses(); - } - chromeos::SetActiveInputMethods(input_method_status_connection_, value); + void StopIme() { + ime_running_ = false; + if (ime_handle_) { + kill(ime_handle_, SIGTERM); + ime_handle_ = 0; + } + if (candidate_window_handle_) { + kill(candidate_window_handle_, SIGTERM); + candidate_window_handle_ = 0; } } -} -void InputMethodLibraryImpl::FlushImeConfig() { - bool active_input_methods_are_changed = false; - bool completed = false; - if (EnsureLoadedAndStarted()) { - InputMethodConfigRequests::iterator iter = pending_config_requests_.begin(); - while (iter != pending_config_requests_.end()) { - const std::string& section = iter->first.first; - const std::string& config_name = iter->first.second; - const ImeConfigValue& value = iter->second; - if (chromeos::SetImeConfig(input_method_status_connection_, - section.c_str(), config_name.c_str(), value)) { - // Check if it's a change in active input methods. - if (config_name == kPreloadEnginesConfigName) { - active_input_methods_are_changed = true; + private: + void MaybeUpdateImeState( + const char* section, + const char* config_name, + const ImeConfigValue& value) { + if (!strcmp(kGeneralSectionName, section) && + !strcmp(kPreloadEnginesConfigName, config_name)) { + if (EnsureLoadedAndStarted()) { + if (value.type == ImeConfigValue::kValueTypeStringList && + value.string_list_value.size() == 1 && + value.string_list_value[0] == kHardwareKeyboardLayout) { + StopInputMethodProcesses(); + } else if (!defer_ime_startup_) { + StartInputMethodProcesses(); } - // Successfully sent. Remove the command and proceed to the next one. - pending_config_requests_.erase(iter++); - } else { - // If SetImeConfig() fails, subsequent calls will likely fail. - break; + chromeos::SetActiveInputMethods(input_method_status_connection_, value); } } - if (pending_config_requests_.empty()) { - // Calls to ChangeInputMethod() will fail if the input method has not yet - // been added to preload_engines. As such, the call is deferred until - // after all config values have been sent to the IME process. - if (need_input_method_set_) { - if (chromeos::ChangeInputMethod(input_method_status_connection_, - active_input_method_.c_str())) { - need_input_method_set_ = false; + } + + void FlushImeConfig() { + bool active_input_methods_are_changed = false; + bool completed = false; + if (EnsureLoadedAndStarted()) { + InputMethodConfigRequests::iterator iter = + pending_config_requests_.begin(); + while (iter != pending_config_requests_.end()) { + const std::string& section = iter->first.first; + const std::string& config_name = iter->first.second; + const ImeConfigValue& value = iter->second; + if (chromeos::SetImeConfig(input_method_status_connection_, + section.c_str(), + config_name.c_str(), + value)) { + // Check if it's a change in active input methods. + if (config_name == kPreloadEnginesConfigName) { + active_input_methods_are_changed = true; + } + // Successfully sent. Remove the command and proceed to the next one. + pending_config_requests_.erase(iter++); + } else { + // If SetImeConfig() fails, subsequent calls will likely fail. + break; + } + } + if (pending_config_requests_.empty()) { + // Calls to ChangeInputMethod() will fail if the input method has not + // yet been added to preload_engines. As such, the call is deferred + // until after all config values have been sent to the IME process. + if (need_input_method_set_) { + if (chromeos::ChangeInputMethod(input_method_status_connection_, + active_input_method_.c_str())) { + need_input_method_set_ = false; + completed = true; + active_input_methods_are_changed = true; + } + } else { completed = true; - active_input_methods_are_changed = true; } - } else { - completed = true; } } - } - if (completed) { - timer_.Stop(); // no-op if it's not running. - } else { - if (!timer_.IsRunning()) { - static const int64 kTimerIntervalInMsec = 100; - timer_.Start(base::TimeDelta::FromMilliseconds(kTimerIntervalInMsec), - this, &InputMethodLibraryImpl::FlushImeConfig); + if (completed) { + timer_.Stop(); // no-op if it's not running. + } else { + if (!timer_.IsRunning()) { + static const int64 kTimerIntervalInMsec = 100; + timer_.Start(base::TimeDelta::FromMilliseconds(kTimerIntervalInMsec), + this, &InputMethodLibraryImpl::FlushImeConfig); + } + } + if (active_input_methods_are_changed) { + FOR_EACH_OBSERVER(Observer, observers_, ActiveInputMethodsChanged(this)); } } - if (active_input_methods_are_changed) { - FOR_EACH_OBSERVER(Observer, observers_, ActiveInputMethodsChanged(this)); + + static void InputMethodChangedHandler( + void* object, + const chromeos::InputMethodDescriptor& current_input_method) { + InputMethodLibraryImpl* input_method_library = + static_cast<InputMethodLibraryImpl*>(object); + input_method_library->UpdateCurrentInputMethod(current_input_method); } -} -// static -void InputMethodLibraryImpl::InputMethodChangedHandler( - void* object, const chromeos::InputMethodDescriptor& current_input_method) { - InputMethodLibraryImpl* input_method_library = - static_cast<InputMethodLibraryImpl*>(object); - input_method_library->UpdateCurrentInputMethod(current_input_method); -} + static void RegisterPropertiesHandler( + void* object, const ImePropertyList& prop_list) { + InputMethodLibraryImpl* input_method_library = + static_cast<InputMethodLibraryImpl*>(object); + input_method_library->RegisterProperties(prop_list); + } -// static -void InputMethodLibraryImpl::RegisterPropertiesHandler( - void* object, const ImePropertyList& prop_list) { - InputMethodLibraryImpl* input_method_library = - static_cast<InputMethodLibraryImpl*>(object); - input_method_library->RegisterProperties(prop_list); -} + static void UpdatePropertyHandler( + void* object, const ImePropertyList& prop_list) { + InputMethodLibraryImpl* input_method_library = + static_cast<InputMethodLibraryImpl*>(object); + input_method_library->UpdateProperty(prop_list); + } -// static -void InputMethodLibraryImpl::UpdatePropertyHandler( - void* object, const ImePropertyList& prop_list) { - InputMethodLibraryImpl* input_method_library = - static_cast<InputMethodLibraryImpl*>(object); - input_method_library->UpdateProperty(prop_list); -} + static void ConnectionChangeHandler(void* object, bool connected) { + InputMethodLibraryImpl* input_method_library = + static_cast<InputMethodLibraryImpl*>(object); + input_method_library->ime_connected_ = connected; + if (connected) { + input_method_library->pending_config_requests_.clear(); + input_method_library->pending_config_requests_.insert( + input_method_library->current_config_values_.begin(), + input_method_library->current_config_values_.end()); + // When the IME process starts up, the hardware layout will be the current + // method. If this is not correct, we'll need to explicitly change it. + if (input_method_library->active_input_method_ != + kHardwareKeyboardLayout) { + input_method_library->need_input_method_set_ = true; + } + input_method_library->FlushImeConfig(); + } else { + // Stop attempting to resend config data, since it will continue to fail. + input_method_library->timer_.Stop(); // no-op if it's not running. + } + } -// static -void InputMethodLibraryImpl::ConnectionChangeHandler(void* object, - bool connected) { - InputMethodLibraryImpl* input_method_library = - static_cast<InputMethodLibraryImpl*>(object); - input_method_library->ime_connected_ = connected; - if (connected) { - input_method_library->pending_config_requests_.clear(); - input_method_library->pending_config_requests_.insert( - input_method_library->current_config_values_.begin(), - input_method_library->current_config_values_.end()); - // When the IME process starts up, the hardware layout will be the current - // method. If this is not correct, we'll need to explicitly change it. - if (input_method_library->active_input_method_ != kHardwareKeyboardLayout) { - input_method_library->need_input_method_set_ = true; + bool EnsureStarted() { + if (!input_method_status_connection_) { + input_method_status_connection_ = chromeos::MonitorInputMethodStatus( + this, + &InputMethodChangedHandler, + &RegisterPropertiesHandler, + &UpdatePropertyHandler, + &ConnectionChangeHandler); } - input_method_library->FlushImeConfig(); - } else { - // Stop attempting to resend config data, since it will continue to fail. - input_method_library->timer_.Stop(); // no-op if it's not running. + return true; } -} -bool InputMethodLibraryImpl::EnsureStarted() { - if (!input_method_status_connection_) { - input_method_status_connection_ = chromeos::MonitorInputMethodStatus( - this, - &InputMethodChangedHandler, - &RegisterPropertiesHandler, - &UpdatePropertyHandler, - &ConnectionChangeHandler); + bool EnsureLoadedAndStarted() { + return CrosLibrary::Get()->EnsureLoaded() && + EnsureStarted(); } - return true; -} -bool InputMethodLibraryImpl::EnsureLoadedAndStarted() { - return CrosLibrary::Get()->EnsureLoaded() && - EnsureStarted(); -} + void UpdateCurrentInputMethod(const InputMethodDescriptor& new_input_method) { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + DLOG(INFO) << "UpdateCurrentInputMethod (Background thread)"; + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + // NewRunnableMethod() copies |new_input_method| by value. + NewRunnableMethod( + this, &InputMethodLibraryImpl::UpdateCurrentInputMethod, + new_input_method)); + return; + } -void InputMethodLibraryImpl::UpdateCurrentInputMethod( - const chromeos::InputMethodDescriptor& new_input_method) { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - DLOG(INFO) << "UpdateCurrentInputMethod (Background thread)"; - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - // NewRunnableMethod() copies |new_input_method| by value. - NewRunnableMethod( - this, &InputMethodLibraryImpl::UpdateCurrentInputMethod, - new_input_method)); - return; - } - - DLOG(INFO) << "UpdateCurrentInputMethod (UI thread)"; - // Change the keyboard layout to a preferred layout for the input method. - CrosLibrary::Get()->GetKeyboardLibrary()->SetCurrentKeyboardLayoutByName( - new_input_method.keyboard_layout); - - if (current_input_method_.id != new_input_method.id) { - previous_input_method_ = current_input_method_; - current_input_method_ = new_input_method; - } - FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this)); -} + DLOG(INFO) << "UpdateCurrentInputMethod (UI thread)"; + // Change the keyboard layout to a preferred layout for the input method. + CrosLibrary::Get()->GetKeyboardLibrary()->SetCurrentKeyboardLayoutByName( + new_input_method.keyboard_layout); -void InputMethodLibraryImpl::RegisterProperties( - const ImePropertyList& prop_list) { - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod( - this, &InputMethodLibraryImpl::RegisterProperties, prop_list)); - return; + if (current_input_method_.id != new_input_method.id) { + previous_input_method_ = current_input_method_; + current_input_method_ = new_input_method; + } + FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this)); } - // |prop_list| might be empty. This means "clear all properties." - current_ime_properties_ = prop_list; - FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this)); -} + void RegisterProperties(const ImePropertyList& prop_list) { + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod( + this, &InputMethodLibraryImpl::RegisterProperties, prop_list)); + return; + } -void InputMethodLibraryImpl::UpdateProperty(const ImePropertyList& prop_list) { - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod( - this, &InputMethodLibraryImpl::UpdateProperty, prop_list)); - return; + // |prop_list| might be empty. This means "clear all properties." + current_ime_properties_ = prop_list; + FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this)); } - for (size_t i = 0; i < prop_list.size(); ++i) { - FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_); + void StartInputMethodProcesses() { + ime_running_ = true; + MaybeLaunchIme(); } - FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this)); -} -void InputMethodLibraryImpl::StartInputMethodProcesses() { - ime_running_ = true; - MaybeLaunchIme(); -} + void UpdateProperty(const ImePropertyList& prop_list) { + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod( + this, &InputMethodLibraryImpl::UpdateProperty, prop_list)); + return; + } -void InputMethodLibraryImpl::MaybeLaunchIme() { - if (!ime_running_) { - return; + for (size_t i = 0; i < prop_list.size(); ++i) { + FindAndUpdateProperty(prop_list[i], ¤t_ime_properties_); + } + FOR_EACH_OBSERVER(Observer, observers_, ImePropertiesChanged(this)); } - // TODO(zork): export "LD_PRELOAD=/usr/lib/libcrash.so" - GSpawnFlags flags = G_SPAWN_DO_NOT_REAP_CHILD; - if (ime_handle_ == 0) { - GError *error = NULL; - gchar **argv; - gint argc; - - if (!g_shell_parse_argv( - "/usr/bin/ibus-daemon --panel=disable --cache=none --restart", - &argc, &argv, &error)) { - LOG(ERROR) << "Could not parse command: " << error->message; - g_error_free(error); + void MaybeLaunchIme() { + if (!ime_running_) { return; } - error = NULL; - int handle; - // TODO(zork): Send output to /var/log/ibus.log - gboolean result = g_spawn_async(NULL, argv, NULL, - flags, NULL, NULL, - &handle, &error); - g_strfreev(argv); - if (!result) { - LOG(ERROR) << "Could not launch ime: " << error->message; - g_error_free(error); - return; + // TODO(zork): export "LD_PRELOAD=/usr/lib/libcrash.so" + GSpawnFlags flags = G_SPAWN_DO_NOT_REAP_CHILD; + if (ime_handle_ == 0) { + GError *error = NULL; + gchar **argv; + gint argc; + + if (!g_shell_parse_argv( + "/usr/bin/ibus-daemon --panel=disable --cache=none --restart", + &argc, &argv, &error)) { + LOG(ERROR) << "Could not parse command: " << error->message; + g_error_free(error); + return; + } + + error = NULL; + int handle; + // TODO(zork): Send output to /var/log/ibus.log + gboolean result = g_spawn_async(NULL, argv, NULL, + flags, NULL, NULL, + &handle, &error); + g_strfreev(argv); + if (!result) { + LOG(ERROR) << "Could not launch ime: " << error->message; + g_error_free(error); + return; + } + ime_handle_ = handle; + g_child_watch_add(ime_handle_, (GChildWatchFunc)OnImeShutdown, this); } - ime_handle_ = handle; - g_child_watch_add(ime_handle_, (GChildWatchFunc)OnImeShutdown, this); - } - if (candidate_window_handle_ == 0) { - GError *error = NULL; - gchar **argv; - gint argc; + if (candidate_window_handle_ == 0) { + GError *error = NULL; + gchar **argv; + gint argc; - if (!g_shell_parse_argv("/opt/google/chrome/candidate_window", - &argc, &argv, &error)) { - LOG(ERROR) << "Could not parse command: " << error->message; - g_error_free(error); - return; + if (!g_shell_parse_argv("/opt/google/chrome/candidate_window", + &argc, &argv, &error)) { + LOG(ERROR) << "Could not parse command: " << error->message; + g_error_free(error); + return; + } + + error = NULL; + int handle; + gboolean result = g_spawn_async(NULL, argv, NULL, + flags, NULL, NULL, + &handle, &error); + g_strfreev(argv); + if (!result) { + LOG(ERROR) << "Could not launch ime candidate window" << error->message; + g_error_free(error); + return; + } + candidate_window_handle_ = handle; + g_child_watch_add(candidate_window_handle_, + (GChildWatchFunc)OnImeShutdown, this); } + } - error = NULL; - int handle; - gboolean result = g_spawn_async(NULL, argv, NULL, - flags, NULL, NULL, - &handle, &error); - g_strfreev(argv); - if (!result) { - LOG(ERROR) << "Could not launch ime candidate window" << error->message; - g_error_free(error); - return; + static void OnImeShutdown(int pid, + int status, + InputMethodLibraryImpl* library) { + g_spawn_close_pid(pid); + if (library->ime_handle_ == pid) { + library->ime_handle_ = 0; + } else if (library->candidate_window_handle_ == pid) { + library->candidate_window_handle_ = 0; } - candidate_window_handle_ = handle; - g_child_watch_add(candidate_window_handle_, - (GChildWatchFunc)OnImeShutdown, this); + + library->MaybeLaunchIme(); } -} -void InputMethodLibraryImpl::StopInputMethodProcesses() { - ime_running_ = false; - if (ime_handle_) { - kill(ime_handle_, SIGTERM); - ime_handle_ = 0; + void StopInputMethodProcesses() { + ime_running_ = false; + if (ime_handle_) { + kill(ime_handle_, SIGTERM); + ime_handle_ = 0; + } } - if (candidate_window_handle_) { - kill(candidate_window_handle_, SIGTERM); - candidate_window_handle_ = 0; + + void SetDeferImeStartup(bool defer) { + defer_ime_startup_ = defer; + } + // A reference to the language api, to allow callbacks when the input method + // status changes. + InputMethodStatusConnection* input_method_status_connection_; + ObserverList<Observer> observers_; + + // The input method which was/is selected. + InputMethodDescriptor previous_input_method_; + InputMethodDescriptor current_input_method_; + + // The input method properties which the current input method uses. The list + // might be empty when no input method is used. + ImePropertyList current_ime_properties_; + + typedef std::pair<std::string, std::string> ConfigKeyType; + typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests; + // SetImeConfig requests that are not yet completed. + // Use a map to queue config requests, so we only send the last request for + // the same config key (i.e. we'll discard ealier requests for the same + // config key). As we discard old requests for the same config key, the order + // of requests doesn't matter, so it's safe to use a map. + InputMethodConfigRequests pending_config_requests_; + + // Values that have been set via SetImeConfig(). We keep a copy available to + // resend if the ime restarts and loses its state. + InputMethodConfigRequests current_config_values_; + + // A timer for retrying to send |pendning_config_commands_| to the input + // method config daemon. + base::OneShotTimer<InputMethodLibraryImpl> timer_; + + bool ime_running_; + bool ime_connected_; + bool defer_ime_startup_; + std::string active_input_method_; + bool need_input_method_set_; + + int ime_handle_; + int candidate_window_handle_; + + DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl); +}; + +InputMethodLibraryImpl::Observer::~Observer() {} + +class InputMethodLibraryStubImpl : public InputMethodLibrary { + public: + InputMethodLibraryStubImpl() + : previous_input_method_("", "", "", ""), + current_input_method_("", "", "", "") { } -} -void InputMethodLibraryImpl::SetDeferImeStartup(bool defer) { - defer_ime_startup_ = defer; -} + ~InputMethodLibraryStubImpl() {} + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} -// static -void InputMethodLibraryImpl::OnImeShutdown(int pid, int status, - InputMethodLibraryImpl* library) { - g_spawn_close_pid(pid); - if (library->ime_handle_ == pid) { - library->ime_handle_ = 0; - } else if (library->candidate_window_handle_ == pid) { - library->candidate_window_handle_ = 0; + InputMethodDescriptors* GetActiveInputMethods() { + return CreateFallbackInputMethodDescriptors(); + } + + + size_t GetNumActiveInputMethods() { + return CreateFallbackInputMethodDescriptors()->size(); } - library->MaybeLaunchIme(); + InputMethodDescriptors* GetSupportedInputMethods() { + return CreateFallbackInputMethodDescriptors(); + } + + void ChangeInputMethod(const std::string& input_method_id) {} + void SetImePropertyActivated(const std::string& key, bool activated) {} + + bool InputMethodIsActivated(const std::string& input_method_id) { + return true; + } + + bool GetImeConfig(const char* section, + const char* config_name, + ImeConfigValue* out_value) { + return false; + } + + bool SetImeConfig(const char* section, + const char* config_name, + const ImeConfigValue& value) { + return false; + } + + virtual const InputMethodDescriptor& previous_input_method() const { + return previous_input_method_; + } + + virtual const InputMethodDescriptor& current_input_method() const { + return current_input_method_; + } + + virtual const ImePropertyList& current_ime_properties() const { + return current_ime_properties_; + } + + virtual void StartInputMethodProcesses() {} + virtual void StopInputMethodProcesses() {} + virtual void SetDeferImeStartup(bool defer) {} + + private: + InputMethodDescriptor previous_input_method_; + InputMethodDescriptor current_input_method_; + ImePropertyList current_ime_properties_; + + DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryStubImpl); +}; + +// static +InputMethodLibrary* InputMethodLibrary::GetImpl(bool stub) { + if (stub) + return new InputMethodLibraryStubImpl(); + else + return new InputMethodLibraryImpl(); } } // namespace chromeos + +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::InputMethodLibraryImpl); + diff --git a/chrome/browser/chromeos/cros/input_method_library.h b/chrome/browser/chromeos/cros/input_method_library.h index daa4c4a..685fa21 100644 --- a/chrome/browser/chromeos/cros/input_method_library.h +++ b/chrome/browser/chromeos/cros/input_method_library.h @@ -95,140 +95,9 @@ class InputMethodLibrary { virtual const InputMethodDescriptor& current_input_method() const = 0; virtual const ImePropertyList& current_ime_properties() const = 0; -}; -// This class handles the interaction with the ChromeOS language library APIs. -// Classes can add themselves as observers. Users can get an instance of this -// library class like this: InputMethodLibrary::Get() -class InputMethodLibraryImpl : public InputMethodLibrary { - public: - InputMethodLibraryImpl(); - virtual ~InputMethodLibraryImpl(); - - // InputMethodLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - virtual InputMethodDescriptors* GetActiveInputMethods(); - virtual size_t GetNumActiveInputMethods(); - virtual InputMethodDescriptors* GetSupportedInputMethods(); - virtual void ChangeInputMethod(const std::string& input_method_id); - virtual void SetImePropertyActivated(const std::string& key, - bool activated); - virtual bool InputMethodIsActivated(const std::string& input_method_id); - virtual bool GetImeConfig( - const char* section, const char* config_name, ImeConfigValue* out_value); - virtual bool SetImeConfig(const char* section, - const char* config_name, - const ImeConfigValue& value); - - virtual const InputMethodDescriptor& previous_input_method() const { - return previous_input_method_; - } - virtual const InputMethodDescriptor& current_input_method() const { - return current_input_method_; - } - - virtual const ImePropertyList& current_ime_properties() const { - return current_ime_properties_; - } - - virtual void StartInputMethodProcesses(); - virtual void StopInputMethodProcesses(); - virtual void SetDeferImeStartup(bool defer); - - private: - // This method is called when there's a change in input method status. - static void InputMethodChangedHandler( - void* object, const InputMethodDescriptor& current_input_method); - - // This method is called when an input method sends "RegisterProperties" - // signal. - static void RegisterPropertiesHandler( - void* object, const ImePropertyList& prop_list); - - // This method is called when an input method sends "UpdateProperty" signal. - static void UpdatePropertyHandler( - void* object, const ImePropertyList& prop_list); - - // This method is called when bus connects or disconnects. - static void ConnectionChangeHandler(void* object, bool connected); - - // Ensures that the monitoring of input method changes is started. Starts - // the monitoring if necessary. Returns true if the monitoring has been - // successfully started. - bool EnsureStarted(); - - // Ensures that the cros library is loaded and the the monitoring is - // started. Loads the cros library and starts the monitoring if - // necessary. Returns true if the two conditions are both met. - bool EnsureLoadedAndStarted(); - - // Called by the handler to update the input method status. - // This will notify all the Observers. - void UpdateCurrentInputMethod( - const InputMethodDescriptor& current_input_method); - - // Called by the handler to register input method properties. - void RegisterProperties(const ImePropertyList& prop_list); - - // Called by the handler to update input method properties. - void UpdateProperty(const ImePropertyList& prop_list); - - void MaybeUpdateImeState(const char* section, const char* config_name, - const ImeConfigValue& value); - - // Tries to send all pending SetImeConfig requests to the input method config - // daemon. - void FlushImeConfig(); - - // Launch any IME processes that should currently be running, but aren't. - void MaybeLaunchIme(); - - // Handle one of the ime processes shutting down. If it was shutdown by us, - // just close the handle. If it crashed, restart it. - static void OnImeShutdown(int pid, int status, - InputMethodLibraryImpl* library); - - // A reference to the language api, to allow callbacks when the input method - // status changes. - InputMethodStatusConnection* input_method_status_connection_; - ObserverList<Observer> observers_; - - // The input method which was/is selected. - InputMethodDescriptor previous_input_method_; - InputMethodDescriptor current_input_method_; - - // The input method properties which the current input method uses. The list - // might be empty when no input method is used. - ImePropertyList current_ime_properties_; - - typedef std::pair<std::string, std::string> ConfigKeyType; - typedef std::map<ConfigKeyType, ImeConfigValue> InputMethodConfigRequests; - // SetImeConfig requests that are not yet completed. - // Use a map to queue config requests, so we only send the last request for - // the same config key (i.e. we'll discard ealier requests for the same - // config key). As we discard old requests for the same config key, the order - // of requests doesn't matter, so it's safe to use a map. - InputMethodConfigRequests pending_config_requests_; - - // Values that have been set via SetImeConfig(). We keep a copy available to - // resend if the ime restarts and loses its state. - InputMethodConfigRequests current_config_values_; - - // A timer for retrying to send |pendning_config_commands_| to the input - // method config daemon. - base::OneShotTimer<InputMethodLibraryImpl> timer_; - - bool ime_running_; - bool ime_connected_; - bool defer_ime_startup_; - std::string active_input_method_; - bool need_input_method_set_; - - int ime_handle_; - int candidate_window_handle_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodLibraryImpl); + // Get library implementation. + static InputMethodLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/keyboard_library.cc b/chrome/browser/chromeos/cros/keyboard_library.cc index dce8442..552d818 100644 --- a/chrome/browser/chromeos/cros/keyboard_library.cc +++ b/chrome/browser/chromeos/cros/keyboard_library.cc @@ -9,41 +9,85 @@ namespace chromeos { -std::string KeyboardLibraryImpl::GetCurrentKeyboardLayoutName() const { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::GetCurrentKeyboardLayoutName(); +class KeyboardLibraryImpl : public KeyboardLibrary { + public: + KeyboardLibraryImpl() {} + virtual ~KeyboardLibraryImpl() {} + + std::string GetCurrentKeyboardLayoutName() const { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::GetCurrentKeyboardLayoutName(); + } + return ""; } - return ""; -} -bool KeyboardLibraryImpl::SetCurrentKeyboardLayoutByName( - const std::string& layout_name) { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::SetCurrentKeyboardLayoutByName(layout_name); + bool SetCurrentKeyboardLayoutByName(const std::string& layout_name) { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::SetCurrentKeyboardLayoutByName(layout_name); + } + return false; } - return false; -} -bool KeyboardLibraryImpl::RemapModifierKeys(const ModifierMap& modifier_map) { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::RemapModifierKeys(modifier_map); + bool RemapModifierKeys(const ModifierMap& modifier_map) { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::RemapModifierKeys(modifier_map); + } + return false; } - return false; -} -bool KeyboardLibraryImpl::GetKeyboardLayoutPerWindow( - bool* is_per_window) const { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::GetKeyboardLayoutPerWindow(is_per_window); + bool GetKeyboardLayoutPerWindow(bool* is_per_window) const { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::GetKeyboardLayoutPerWindow(is_per_window); + } + return false; } - return false; -} -bool KeyboardLibraryImpl::SetKeyboardLayoutPerWindow(bool is_per_window) { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::SetKeyboardLayoutPerWindow(is_per_window); + bool SetKeyboardLayoutPerWindow(bool is_per_window) { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::SetKeyboardLayoutPerWindow(is_per_window); + } + return false; } - return false; + + private: + DISALLOW_COPY_AND_ASSIGN(KeyboardLibraryImpl); +}; + +class KeyboardLibraryStubImpl : public KeyboardLibrary { + public: + KeyboardLibraryStubImpl() {} + virtual ~KeyboardLibraryStubImpl() {} + + std::string GetCurrentKeyboardLayoutName() const { + return ""; + } + + bool SetCurrentKeyboardLayoutByName(const std::string& layout_name) { + return false; + } + + bool RemapModifierKeys(const ModifierMap& modifier_map) { + return false; + } + + bool GetKeyboardLayoutPerWindow(bool* is_per_window) const { + return false; + } + + bool SetKeyboardLayoutPerWindow(bool is_per_window) { + return false; + } + + private: + DISALLOW_COPY_AND_ASSIGN(KeyboardLibraryStubImpl); +}; + +// static +KeyboardLibrary* KeyboardLibrary::GetImpl(bool stub) { + if (stub) + return new KeyboardLibraryStubImpl(); + else + return new KeyboardLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/keyboard_library.h b/chrome/browser/chromeos/cros/keyboard_library.h index ab1b12e..0a160d5 100644 --- a/chrome/browser/chromeos/cros/keyboard_library.h +++ b/chrome/browser/chromeos/cros/keyboard_library.h @@ -38,22 +38,9 @@ class KeyboardLibrary { // is given, the same keyboard layout will be shared for all applications. // Returns true on success. virtual bool SetKeyboardLayoutPerWindow(bool is_per_window) = 0; -}; -class KeyboardLibraryImpl : public KeyboardLibrary { - public: - KeyboardLibraryImpl() {} - virtual ~KeyboardLibraryImpl() {} - - // KeyboardLibrary overrides. - virtual std::string GetCurrentKeyboardLayoutName() const; - virtual bool SetCurrentKeyboardLayoutByName(const std::string& layout_name); - virtual bool RemapModifierKeys(const ModifierMap& modifier_map); - virtual bool GetKeyboardLayoutPerWindow(bool* is_per_window) const; - virtual bool SetKeyboardLayoutPerWindow(bool is_per_window); - - private: - DISALLOW_COPY_AND_ASSIGN(KeyboardLibraryImpl); + // Get library implementation. + static KeyboardLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/login_library.cc b/chrome/browser/chromeos/cros/login_library.cc index efd8536..341cf59 100644 --- a/chrome/browser/chromeos/cros/login_library.cc +++ b/chrome/browser/chromeos/cros/login_library.cc @@ -10,19 +10,50 @@ namespace chromeos { -bool LoginLibraryImpl::EmitLoginPromptReady() { - return chromeos::EmitLoginPromptReady(); -} +class LoginLibraryImpl : public LoginLibrary { + public: + LoginLibraryImpl() {} + virtual ~LoginLibraryImpl() {} -bool LoginLibraryImpl::StartSession(const std::string& user_email, - const std::string& unique_id /* unused */) { - // only pass unique_id through once we use it for something. - return chromeos::StartSession(user_email.c_str(), ""); -} + bool EmitLoginPromptReady() { + return chromeos::EmitLoginPromptReady(); + } + + bool StartSession(const std::string& user_email, + const std::string& unique_id /* unused */) { + // only pass unique_id through once we use it for something. + return chromeos::StartSession(user_email.c_str(), ""); + } + + bool StopSession(const std::string& unique_id /* unused */) { + // only pass unique_id through once we use it for something. + return chromeos::StopSession(""); + } + + private: + DISALLOW_COPY_AND_ASSIGN(LoginLibraryImpl); +}; + +class LoginLibraryStubImpl : public LoginLibrary { + public: + LoginLibraryStubImpl() {} + virtual ~LoginLibraryStubImpl() {} + + bool EmitLoginPromptReady() { return true; } + bool StartSession(const std::string& user_email, + const std::string& unique_id /* unused */) { return true; } + bool StopSession(const std::string& unique_id /* unused */) { return true; } + + private: + DISALLOW_COPY_AND_ASSIGN(LoginLibraryStubImpl); +}; -bool LoginLibraryImpl::StopSession(const std::string& unique_id /* unused */) { - // only pass unique_id through once we use it for something. - return chromeos::StopSession(""); +// static +LoginLibrary* LoginLibrary::GetImpl(bool stub) { + if (stub) + return new LoginLibraryStubImpl(); + else + return new LoginLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/login_library.h b/chrome/browser/chromeos/cros/login_library.h index b8f2b6c..292d412 100644 --- a/chrome/browser/chromeos/cros/login_library.h +++ b/chrome/browser/chromeos/cros/login_library.h @@ -32,22 +32,9 @@ class LoginLibrary { // This will tell the session manager to terminate the session for the user // indicated by |unique_id|. virtual bool StopSession(const std::string& unique_id /* unused */) = 0; -}; - -// This class handles the interaction with the ChromeOS login library APIs. -class LoginLibraryImpl : public LoginLibrary { - public: - LoginLibraryImpl() {} - virtual ~LoginLibraryImpl() {} - - // LoginLibrary overrides. - virtual bool EmitLoginPromptReady(); - virtual bool StartSession(const std::string& user_email, - const std::string& unique_id /* unused */); - virtual bool StopSession(const std::string& unique_id /* unused */); - private: - DISALLOW_COPY_AND_ASSIGN(LoginLibraryImpl); + // Get library implementation. + static LoginLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/mount_library.cc b/chrome/browser/chromeos/cros/mount_library.cc index e99edf2..16cec4a 100644 --- a/chrome/browser/chromeos/cros/mount_library.cc +++ b/chrome/browser/chromeos/cros/mount_library.cc @@ -9,97 +9,140 @@ #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::MountLibraryImpl); - namespace chromeos { -void MountLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} +class MountLibraryImpl : public MountLibrary { + public: + MountLibraryImpl() : mount_status_connection_(NULL) { + if (CrosLibrary::Get()->EnsureLoaded()) { + Init(); + } else { + LOG(ERROR) << "Cros Library has not been loaded"; + } + } -void MountLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + ~MountLibraryImpl() { + if (mount_status_connection_) { + DisconnectMountStatus(mount_status_connection_); + } + } -bool MountLibraryImpl::MountPath(const char* device_path) { - return MountDevicePath(device_path); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void MountLibraryImpl::ParseDisks(const MountStatus& status) { - disks_.clear(); - for (int i = 0; i < status.size; i++) { - std::string path; - std::string mountpath; - std::string systempath; - bool parent; - bool hasmedia; - if (status.disks[i].path != NULL) { - path = status.disks[i].path; - } - if (status.disks[i].mountpath != NULL) { - mountpath = status.disks[i].mountpath; - } - if (status.disks[i].systempath != NULL) { - systempath = status.disks[i].systempath; + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } + + bool MountPath(const char* device_path) { + return MountDevicePath(device_path); + } + + const DiskVector& disks() const { return disks_; } + + private: + void ParseDisks(const MountStatus& status) { + disks_.clear(); + for (int i = 0; i < status.size; i++) { + std::string path; + std::string mountpath; + std::string systempath; + bool parent; + bool hasmedia; + if (status.disks[i].path != NULL) { + path = status.disks[i].path; + } + if (status.disks[i].mountpath != NULL) { + mountpath = status.disks[i].mountpath; + } + if (status.disks[i].systempath != NULL) { + systempath = status.disks[i].systempath; + } + parent = status.disks[i].isparent; + hasmedia = status.disks[i].hasmedia; + disks_.push_back(Disk(path, + mountpath, + systempath, + parent, + hasmedia)); } - parent = status.disks[i].isparent; - hasmedia = status.disks[i].hasmedia; - disks_.push_back(Disk(path, - mountpath, - systempath, - parent, - hasmedia)); } -} -MountLibraryImpl::MountLibraryImpl() : mount_status_connection_(NULL) { - if (CrosLibrary::Get()->EnsureLoaded()) { - Init(); - } else { - LOG(ERROR) << "Cros Library has not been loaded"; + static void MountStatusChangedHandler(void* object, + const MountStatus& status, + MountEventType evt, + const char* path) { + MountLibraryImpl* mount = static_cast<MountLibraryImpl*>(object); + std::string devicepath = path; + mount->ParseDisks(status); + mount->UpdateMountStatus(status, evt, devicepath); } -} -MountLibraryImpl::~MountLibraryImpl() { - if (mount_status_connection_) { - DisconnectMountStatus(mount_status_connection_); + void Init() { + // Getting the monitor status so that the daemon starts up. + MountStatus* mount = RetrieveMountInformation(); + if (!mount) { + LOG(ERROR) << "Failed to retrieve mount information"; + return; + } + ParseDisks(*mount); + FreeMountStatus(mount); + + mount_status_connection_ = MonitorMountStatus( + &MountStatusChangedHandler, this); } -} -// static -void MountLibraryImpl::MountStatusChangedHandler(void* object, - const MountStatus& status, - MountEventType evt, - const char* path) { - MountLibraryImpl* mount = static_cast<MountLibraryImpl*>(object); - std::string devicepath = path; - mount->ParseDisks(status); - mount->UpdateMountStatus(status, evt, devicepath); -} + void UpdateMountStatus(const MountStatus& status, + MountEventType evt, + const std::string& path) { + // Make sure we run on UI thread. + DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI)); -void MountLibraryImpl::Init() { - // Getting the monitor status so that the daemon starts up. - MountStatus* mount = RetrieveMountInformation(); - if (!mount) { - LOG(ERROR) << "Failed to retrieve mount information"; - return; + FOR_EACH_OBSERVER( + Observer, observers_, MountChanged(this, evt, path)); } - ParseDisks(*mount); - FreeMountStatus(mount); + ObserverList<Observer> observers_; - mount_status_connection_ = MonitorMountStatus( - &MountStatusChangedHandler, this); -} + // A reference to the mount api, to allow callbacks when the mount + // status changes. + MountStatusConnection mount_status_connection_; + + // The list of disks found. + DiskVector disks_; + + DISALLOW_COPY_AND_ASSIGN(MountLibraryImpl); +}; -void MountLibraryImpl::UpdateMountStatus(const MountStatus& status, - MountEventType evt, - const std::string& path) { - // Make sure we run on UI thread. - DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI)); +class MountLibraryStubImpl : public MountLibrary { + public: + MountLibraryStubImpl() {} + virtual ~MountLibraryStubImpl() {} - FOR_EACH_OBSERVER(Observer, observers_, MountChanged(this, evt, path)); + // MountLibrary overrides. + virtual void AddObserver(Observer* observer) {} + virtual void RemoveObserver(Observer* observer) {} + virtual const DiskVector& disks() const { return disks_; } + virtual bool MountPath(const char* device_path) { return false; } + + private: + // The list of disks found. + DiskVector disks_; + + DISALLOW_COPY_AND_ASSIGN(MountLibraryStubImpl); +}; + +// static +MountLibrary* MountLibrary::GetImpl(bool stub) { + if (stub) + return new MountLibraryStubImpl(); + else + return new MountLibraryImpl(); } } // namespace chromeos + +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::MountLibraryImpl); + diff --git a/chrome/browser/chromeos/cros/mount_library.h b/chrome/browser/chromeos/cros/mount_library.h index 3e99eed..be8660e 100644 --- a/chrome/browser/chromeos/cros/mount_library.h +++ b/chrome/browser/chromeos/cros/mount_library.h @@ -59,51 +59,9 @@ class MountLibrary { virtual void RemoveObserver(Observer* observer) = 0; virtual const DiskVector& disks() const = 0; virtual bool MountPath(const char* device_path) = 0; -}; - -// This class handles the interaction with the ChromeOS mount library APIs. -// Classes can add themselves as observers. Users can get an instance of this -// library class like this: MountLibrary::Get(). -class MountLibraryImpl : public MountLibrary { - public: - MountLibraryImpl(); - virtual ~MountLibraryImpl(); - - // MountLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - virtual const DiskVector& disks() const { return disks_; } - virtual bool MountPath(const char* device_path); - private: - void ParseDisks(const MountStatus& status); - - // This method is called when there's a change in mount status. - // This method is called the UI Thread. - static void MountStatusChangedHandler(void* object, - const MountStatus& status, - MountEventType evt, - const char* path); - - // This methods starts the monitoring of mount changes. - // It should be called on the UI Thread. - void Init(); - - // Called by the handler to update the mount status. - // This will notify all the Observers. - void UpdateMountStatus(const MountStatus& status, - MountEventType evt, - const std::string& path); - - ObserverList<Observer> observers_; - - // A reference to the mount api, to allow callbacks when the mount - // status changes. - MountStatusConnection mount_status_connection_; - - // The list of disks found. - DiskVector disks_; - DISALLOW_COPY_AND_ASSIGN(MountLibraryImpl); + // Get library implementation. + static MountLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/network_library.cc b/chrome/browser/chromeos/cros/network_library.cc index a133c8d..ba49af3 100644 --- a/chrome/browser/chromeos/cros/network_library.cc +++ b/chrome/browser/chromeos/cros/network_library.cc @@ -13,10 +13,6 @@ #include "chrome/browser/chromeos/cros/cros_library.h" #include "net/url_request/url_request_job.h" -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl); - namespace chromeos { static const std::string kGoogleWifi = "Google"; @@ -208,697 +204,911 @@ std::string WifiNetwork::GetEncryptionString() { //////////////////////////////////////////////////////////////////////////////// // NetworkLibrary -// static -const int NetworkLibraryImpl::kNetworkTrafficeTimerSecs = 1; - -NetworkLibraryImpl::NetworkLibraryImpl() - : traffic_type_(0), - network_status_connection_(NULL), - available_devices_(0), - enabled_devices_(0), - connected_devices_(0), - offline_mode_(false) { - if (CrosLibrary::Get()->EnsureLoaded()) { - Init(); - } else { - InitTestData(); - } - g_url_request_job_tracker.AddObserver(this); -} +class NetworkLibraryImpl : public NetworkLibrary, + public URLRequestJobTracker::JobObserver { + public: + NetworkLibraryImpl() + : traffic_type_(0), + network_status_connection_(NULL), + available_devices_(0), + enabled_devices_(0), + connected_devices_(0), + offline_mode_(false) { + if (CrosLibrary::Get()->EnsureLoaded()) { + Init(); + } else { + InitTestData(); + } + g_url_request_job_tracker.AddObserver(this); + } -NetworkLibraryImpl::~NetworkLibraryImpl() { - if (network_status_connection_) { - DisconnectMonitorNetwork(network_status_connection_); + ~NetworkLibraryImpl() { + if (network_status_connection_) { + DisconnectMonitorNetwork(network_status_connection_); + } + g_url_request_job_tracker.RemoveObserver(this); } - g_url_request_job_tracker.RemoveObserver(this); -} -//////////////////////////////////////////////////////////////////////////////// -// NetworkLibraryImpl, URLRequestJobTracker::JobObserver implementation: + ///////////////////////////////////////////////////////////////////////////// + // NetworkLibraryImpl, URLRequestJobTracker::JobObserver implementation: -void NetworkLibraryImpl::OnJobAdded(URLRequestJob* job) { - CheckNetworkTraffic(false); -} + void OnJobAdded(URLRequestJob* job) { + CheckNetworkTraffic(false); + } -void NetworkLibraryImpl::OnJobRemoved(URLRequestJob* job) { - CheckNetworkTraffic(false); -} + void OnJobRemoved(URLRequestJob* job) { + CheckNetworkTraffic(false); + } -void NetworkLibraryImpl::OnJobDone(URLRequestJob* job, - const URLRequestStatus& status) { - CheckNetworkTraffic(false); -} + void OnJobDone(URLRequestJob* job, const URLRequestStatus& status) { + CheckNetworkTraffic(false); + } -void NetworkLibraryImpl::OnJobRedirect(URLRequestJob* job, const GURL& location, - int status_code) { - CheckNetworkTraffic(false); -} + void OnJobRedirect( + URLRequestJob* job, const GURL& location, int status_code) { + CheckNetworkTraffic(false); + } -void NetworkLibraryImpl::OnBytesRead(URLRequestJob* job, int byte_count) { - CheckNetworkTraffic(true); -} + void OnBytesRead(URLRequestJob* job, int byte_count) { + CheckNetworkTraffic(true); + } -void NetworkLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void NetworkLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -//////////////////////////////////////////////////////////////////////////////// + virtual const EthernetNetwork& ethernet_network() const { return ethernet_; } + virtual bool ethernet_connecting() const { return ethernet_.connecting(); } + virtual bool ethernet_connected() const { return ethernet_.connected(); } -bool NetworkLibraryImpl::FindWifiNetworkByPath( - const std::string& path, WifiNetwork* result) const { - const WifiNetwork* wifi = - GetWirelessNetworkByPath(wifi_networks_, path); - if (wifi) { - if (result) - *result = *wifi; - return true; + virtual const std::string& wifi_name() const { return wifi_.name(); } + virtual bool wifi_connecting() const { return wifi_.connecting(); } + virtual bool wifi_connected() const { return wifi_.connected(); } + virtual int wifi_strength() const { return wifi_.strength(); } + + virtual const std::string& cellular_name() const { return cellular_.name(); } + virtual bool cellular_connecting() const { return cellular_.connecting(); } + virtual bool cellular_connected() const { return cellular_.connected(); } + virtual int cellular_strength() const { return cellular_.strength(); } + + bool Connected() const { + return ethernet_connected() || wifi_connected() || cellular_connected(); } - return false; -} -bool NetworkLibraryImpl::FindCellularNetworkByPath( - const std::string& path, CellularNetwork* result) const { - const CellularNetwork* cellular = - GetWirelessNetworkByPath(cellular_networks_, path); - if (cellular) { - if (result) - *result = *cellular; - return true; + bool Connecting() const { + return ethernet_connecting() || wifi_connecting() || cellular_connecting(); } - return false; -} -void NetworkLibraryImpl::RequestWifiScan() { - if (CrosLibrary::Get()->EnsureLoaded()) { - RequestScan(TYPE_WIFI); + const std::string& IPAddress() const { + // Returns highest priority IP address. + if (ethernet_connected()) + return ethernet_.ip_address(); + if (wifi_connected()) + return wifi_.ip_address(); + if (cellular_connected()) + return cellular_.ip_address(); + return ethernet_.ip_address(); } -} -bool NetworkLibraryImpl::GetWifiAccessPoints(WifiAccessPointVector* result) { - if (!CrosLibrary::Get()->EnsureLoaded()) - return false; - DeviceNetworkList* network_list = GetDeviceNetworkList(); - if (network_list == NULL) - return false; - result->clear(); - result->reserve(network_list->network_size); - const base::Time now = base::Time::Now(); - for (size_t i = 0; i < network_list->network_size; ++i) { - DCHECK(network_list->networks[i].address); - DCHECK(network_list->networks[i].name); - WifiAccessPoint ap; - ap.mac_address = network_list->networks[i].address; - ap.name = network_list->networks[i].name; - ap.timestamp = now - - base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds); - ap.signal_strength = network_list->networks[i].strength; - ap.channel = network_list->networks[i].channel; - result->push_back(ap); - } - FreeDeviceNetworkList(network_list); - return true; -} + virtual const WifiNetworkVector& wifi_networks() const { + return wifi_networks_; + } -bool NetworkLibraryImpl::ConnectToPreferredNetworkIfAvailable() { - // TODO(chocobo): Add the concept of preferred network to libcros. - // So that we don't have to hard-code Google-A here. - if (CrosLibrary::Get()->EnsureLoaded()) { - LOG(INFO) << "Attempting to auto-connect to Google wifi."; - // First force a refresh of the system info. - UpdateSystemInfo(); + virtual const WifiNetworkVector& remembered_wifi_networks() const { + return remembered_wifi_networks_; + } - // If ethernet is connected, then don't bother. - if (ethernet_connected()) { - LOG(INFO) << "Ethernet connected, so don't need Google wifi."; - return false; - } + virtual const CellularNetworkVector& cellular_networks() const { + return cellular_networks_; + } - WifiNetwork* wifi = GetPreferredNetwork(); - if (!wifi) { - LOG(INFO) << "Google-A/Google wifi not found or set to not auto-connect."; - return false; + virtual const CellularNetworkVector& remembered_cellular_networks() const { + return remembered_cellular_networks_; + } + + ///////////////////////////////////////////////////////////////////////////// + + bool FindWifiNetworkByPath( + const std::string& path, WifiNetwork* result) const { + const WifiNetwork* wifi = + GetWirelessNetworkByPath(wifi_networks_, path); + if (wifi) { + if (result) + *result = *wifi; + return true; } + return false; + } - // Save the wifi path, so we know which one we want to auto-connect to. - const std::string wifi_path = wifi->service_path(); + bool FindCellularNetworkByPath( + const std::string& path, CellularNetwork* result) const { + const CellularNetwork* cellular = + GetWirelessNetworkByPath(cellular_networks_, path); + if (cellular) { + if (result) + *result = *cellular; + return true; + } + return false; + } - // It takes some time for the enterprise daemon to start up and populate the - // certificate and identity. So we wait at most 3 seconds here. And every - // 100ms, we refetch the system info and check the cert and identify on the - // wifi. The enterprise daemon takes between 0.4 to 0.9 seconds to setup. - bool setup = false; - for (int i = 0; i < 30; i++) { - // Update the system and refetch the network. - UpdateSystemInfo(); - wifi = GetWirelessNetworkByPath(wifi_networks_, wifi_path); - // See if identity and certpath are available. - if (wifi && !wifi->identity().empty() && !wifi->cert_path().empty()) { - LOG(INFO) << "Google wifi set up after " << (i*0.1) << " seconds."; - setup = true; - break; - } - PlatformThread::Sleep(100); + void RequestWifiScan() { + if (CrosLibrary::Get()->EnsureLoaded()) { + RequestScan(TYPE_WIFI); } + } - if (!setup) { - LOG(INFO) << "Google wifi not set up after 3 seconds."; + bool GetWifiAccessPoints(WifiAccessPointVector* result) { + if (!CrosLibrary::Get()->EnsureLoaded()) return false; + DeviceNetworkList* network_list = GetDeviceNetworkList(); + if (network_list == NULL) + return false; + result->clear(); + result->reserve(network_list->network_size); + const base::Time now = base::Time::Now(); + for (size_t i = 0; i < network_list->network_size; ++i) { + DCHECK(network_list->networks[i].address); + DCHECK(network_list->networks[i].name); + WifiAccessPoint ap; + ap.mac_address = network_list->networks[i].address; + ap.name = network_list->networks[i].name; + ap.timestamp = now - + base::TimeDelta::FromSeconds(network_list->networks[i].age_seconds); + ap.signal_strength = network_list->networks[i].strength; + ap.channel = network_list->networks[i].channel; + result->push_back(ap); } - - // Now that we have a setup Google wifi, we can connect to it. - ConnectToNetwork(wifi_path.c_str(), NULL); + FreeDeviceNetworkList(network_list); return true; } - return false; -} -bool NetworkLibraryImpl::PreferredNetworkConnected() { - WifiNetwork* wifi = GetPreferredNetwork(); - return wifi && wifi->connected(); -} + bool ConnectToPreferredNetworkIfAvailable() { + // TODO(chocobo): Add the concept of preferred network to libcros. + // So that we don't have to hard-code Google-A here. + if (CrosLibrary::Get()->EnsureLoaded()) { + LOG(INFO) << "Attempting to auto-connect to Google wifi."; + // First force a refresh of the system info. + UpdateSystemInfo(); -bool NetworkLibraryImpl::PreferredNetworkFailed() { - WifiNetwork* wifi = GetPreferredNetwork(); - return !wifi || wifi->failed(); -} + // If ethernet is connected, then don't bother. + if (ethernet_connected()) { + LOG(INFO) << "Ethernet connected, so don't need Google wifi."; + return false; + } -void NetworkLibraryImpl::ConnectToWifiNetwork(WifiNetwork network, - const std::string& password, - const std::string& identity, - const std::string& certpath) { - if (CrosLibrary::Get()->EnsureLoaded()) { - ConnectToNetworkWithCertInfo(network.service_path().c_str(), - password.empty() ? NULL : password.c_str(), - identity.empty() ? NULL : identity.c_str(), - certpath.empty() ? NULL : certpath.c_str()); + WifiNetwork* wifi = GetPreferredNetwork(); + if (!wifi) { + LOG(INFO) << + "Google-A/Google wifi not found or set to not auto-connect."; + return false; + } + + // Save the wifi path, so we know which one we want to auto-connect to. + const std::string wifi_path = wifi->service_path(); + + // It takes some time for the enterprise daemon to start up and populate + // the certificate and identity. So we wait at most 3 seconds here. And + // every 100ms, we refetch the system info and check the cert and identify + // on the wifi. The enterprise daemon takes between 0.4 to 0.9 seconds to + // setup. + bool setup = false; + for (int i = 0; i < 30; i++) { + // Update the system and refetch the network. + UpdateSystemInfo(); + wifi = GetWirelessNetworkByPath(wifi_networks_, wifi_path); + // See if identity and certpath are available. + if (wifi && !wifi->identity().empty() && !wifi->cert_path().empty()) { + LOG(INFO) << "Google wifi set up after " << (i*0.1) << " seconds."; + setup = true; + break; + } + PlatformThread::Sleep(100); + } + + if (!setup) { + LOG(INFO) << "Google wifi not set up after 3 seconds."; + return false; + } + + // Now that we have a setup Google wifi, we can connect to it. + ConnectToNetwork(wifi_path.c_str(), NULL); + return true; + } + return false; } -} -void NetworkLibraryImpl::ConnectToWifiNetwork(const std::string& ssid, - const std::string& password, - const std::string& identity, - const std::string& certpath, - bool auto_connect) { - if (CrosLibrary::Get()->EnsureLoaded()) { - // First create a service from hidden network. - ServiceInfo* service = GetWifiService(ssid.c_str(), - SECURITY_UNKNOWN); - if (service) { - // Set auto-connect. - SetAutoConnect(service->service_path, auto_connect); - // Now connect to that service. - ConnectToNetworkWithCertInfo(service->service_path, + bool PreferredNetworkConnected() { + WifiNetwork* wifi = GetPreferredNetwork(); + return wifi && wifi->connected(); + } + + bool PreferredNetworkFailed() { + WifiNetwork* wifi = GetPreferredNetwork(); + return !wifi || wifi->failed(); + } + + void ConnectToWifiNetwork(WifiNetwork network, + const std::string& password, + const std::string& identity, + const std::string& certpath) { + if (CrosLibrary::Get()->EnsureLoaded()) { + ConnectToNetworkWithCertInfo(network.service_path().c_str(), password.empty() ? NULL : password.c_str(), identity.empty() ? NULL : identity.c_str(), certpath.empty() ? NULL : certpath.c_str()); - - // Clean up ServiceInfo object. - FreeServiceInfo(service); - } else { - LOG(WARNING) << "Cannot find hidden network: " << ssid; - // TODO(chocobo): Show error message. } } -} -void NetworkLibraryImpl::ConnectToCellularNetwork(CellularNetwork network) { - if (CrosLibrary::Get()->EnsureLoaded()) { - ConnectToNetwork(network.service_path().c_str(), NULL); + void ConnectToWifiNetwork(const std::string& ssid, + const std::string& password, + const std::string& identity, + const std::string& certpath, + bool auto_connect) { + if (CrosLibrary::Get()->EnsureLoaded()) { + // First create a service from hidden network. + ServiceInfo* service = GetWifiService(ssid.c_str(), + SECURITY_UNKNOWN); + if (service) { + // Set auto-connect. + SetAutoConnect(service->service_path, auto_connect); + // Now connect to that service. + ConnectToNetworkWithCertInfo(service->service_path, + password.empty() ? NULL : password.c_str(), + identity.empty() ? NULL : identity.c_str(), + certpath.empty() ? NULL : certpath.c_str()); + + // Clean up ServiceInfo object. + FreeServiceInfo(service); + } else { + LOG(WARNING) << "Cannot find hidden network: " << ssid; + // TODO(chocobo): Show error message. + } + } } -} -void NetworkLibraryImpl::DisconnectFromWirelessNetwork( - const WirelessNetwork& network) { - if (CrosLibrary::Get()->EnsureLoaded()) { - DisconnectFromNetwork(network.service_path().c_str()); + void ConnectToCellularNetwork(CellularNetwork network) { + if (CrosLibrary::Get()->EnsureLoaded()) { + ConnectToNetwork(network.service_path().c_str(), NULL); + } } -} -void NetworkLibraryImpl::SaveCellularNetwork(const CellularNetwork& network) { - // Update the wifi network in the local cache. - CellularNetwork* cellular = GetWirelessNetworkByPath(cellular_networks_, - network.service_path()); - if (cellular) - *cellular = network; - - // Update the cellular network with libcros. - if (CrosLibrary::Get()->EnsureLoaded()) { - SetAutoConnect(network.service_path().c_str(), network.auto_connect()); + void DisconnectFromWirelessNetwork( + const WirelessNetwork& network) { + if (CrosLibrary::Get()->EnsureLoaded()) { + DisconnectFromNetwork(network.service_path().c_str()); + } } -} -void NetworkLibraryImpl::SaveWifiNetwork(const WifiNetwork& network) { - // Update the wifi network in the local cache. - WifiNetwork* wifi = GetWirelessNetworkByPath(wifi_networks_, - network.service_path()); - if (wifi) - *wifi = network; + void SaveCellularNetwork(const CellularNetwork& network) { + // Update the wifi network in the local cache. + CellularNetwork* cellular = GetWirelessNetworkByPath( + cellular_networks_, + network.service_path()); + if (cellular) + *cellular = network; + + // Update the cellular network with libcros. + if (CrosLibrary::Get()->EnsureLoaded()) { + SetAutoConnect(network.service_path().c_str(), network.auto_connect()); + } + } - // Update the wifi network with libcros. - if (CrosLibrary::Get()->EnsureLoaded()) { - SetPassphrase(network.service_path().c_str(), network.passphrase().c_str()); - SetIdentity(network.service_path().c_str(), network.identity().c_str()); - SetCertPath(network.service_path().c_str(), network.cert_path().c_str()); - SetAutoConnect(network.service_path().c_str(), network.auto_connect()); + void SaveWifiNetwork(const WifiNetwork& network) { + // Update the wifi network in the local cache. + WifiNetwork* wifi = GetWirelessNetworkByPath(wifi_networks_, + network.service_path()); + if (wifi) + *wifi = network; + + // Update the wifi network with libcros. + if (CrosLibrary::Get()->EnsureLoaded()) { + SetPassphrase( + network.service_path().c_str(), network.passphrase().c_str()); + SetIdentity(network.service_path().c_str(), network.identity().c_str()); + SetCertPath(network.service_path().c_str(), network.cert_path().c_str()); + SetAutoConnect(network.service_path().c_str(), network.auto_connect()); + } } -} -void NetworkLibraryImpl::ForgetWirelessNetwork( - const std::string& service_path) { - if (CrosLibrary::Get()->EnsureLoaded()) { - DeleteRememberedService(service_path.c_str()); + void ForgetWirelessNetwork( + const std::string& service_path) { + if (CrosLibrary::Get()->EnsureLoaded()) { + DeleteRememberedService(service_path.c_str()); + } } -} -void NetworkLibraryImpl::EnableEthernetNetworkDevice(bool enable) { - EnableNetworkDeviceType(TYPE_ETHERNET, enable); -} + virtual bool ethernet_available() const { + return available_devices_ & (1 << TYPE_ETHERNET); + } + virtual bool wifi_available() const { + return available_devices_ & (1 << TYPE_WIFI); + } + virtual bool cellular_available() const { + return available_devices_ & (1 << TYPE_CELLULAR); + } -void NetworkLibraryImpl::EnableWifiNetworkDevice(bool enable) { - EnableNetworkDeviceType(TYPE_WIFI, enable); -} + virtual bool ethernet_enabled() const { + return enabled_devices_ & (1 << TYPE_ETHERNET); + } + virtual bool wifi_enabled() const { + return enabled_devices_ & (1 << TYPE_WIFI); + } + virtual bool cellular_enabled() const { + return enabled_devices_ & (1 << TYPE_CELLULAR); + } -void NetworkLibraryImpl::EnableCellularNetworkDevice(bool enable) { - EnableNetworkDeviceType(TYPE_CELLULAR, enable); -} + virtual bool offline_mode() const { return offline_mode_; } -void NetworkLibraryImpl::EnableOfflineMode(bool enable) { - if (!CrosLibrary::Get()->EnsureLoaded()) - return; + void EnableEthernetNetworkDevice(bool enable) { + EnableNetworkDeviceType(TYPE_ETHERNET, enable); + } - // If network device is already enabled/disabled, then don't do anything. - if (enable && offline_mode_) { - LOG(INFO) << "Trying to enable offline mode when it's already enabled. "; - return; + void EnableWifiNetworkDevice(bool enable) { + EnableNetworkDeviceType(TYPE_WIFI, enable); } - if (!enable && !offline_mode_) { - LOG(INFO) << "Trying to disable offline mode when it's already disabled. "; - return; + + void EnableCellularNetworkDevice(bool enable) { + EnableNetworkDeviceType(TYPE_CELLULAR, enable); } - if (SetOfflineMode(enable)) { - offline_mode_ = enable; + void EnableOfflineMode(bool enable) { + if (!CrosLibrary::Get()->EnsureLoaded()) + return; + + // If network device is already enabled/disabled, then don't do anything. + if (enable && offline_mode_) { + LOG(INFO) << "Trying to enable offline mode when it's already enabled. "; + return; + } + if (!enable && !offline_mode_) { + LOG(INFO) << + "Trying to disable offline mode when it's already disabled. "; + return; + } + + if (SetOfflineMode(enable)) { + offline_mode_ = enable; + } } -} -NetworkIPConfigVector NetworkLibraryImpl::GetIPConfigs( - const std::string& device_path) { - NetworkIPConfigVector ipconfig_vector; - if (!device_path.empty()) { - IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str()); - if (ipconfig_status) { - for (int i = 0; i < ipconfig_status->size; i++) { - IPConfig ipconfig = ipconfig_status->ips[i]; - ipconfig_vector.push_back( - NetworkIPConfig(device_path, ipconfig.type, ipconfig.address, - ipconfig.netmask, ipconfig.gateway, - ipconfig.name_servers)); + NetworkIPConfigVector GetIPConfigs( + const std::string& device_path) { + NetworkIPConfigVector ipconfig_vector; + if (!device_path.empty()) { + IPConfigStatus* ipconfig_status = ListIPConfigs(device_path.c_str()); + if (ipconfig_status) { + for (int i = 0; i < ipconfig_status->size; i++) { + IPConfig ipconfig = ipconfig_status->ips[i]; + ipconfig_vector.push_back( + NetworkIPConfig(device_path, ipconfig.type, ipconfig.address, + ipconfig.netmask, ipconfig.gateway, + ipconfig.name_servers)); + } + FreeIPConfigStatus(ipconfig_status); + // Sort the list of ip configs by type. + std::sort(ipconfig_vector.begin(), ipconfig_vector.end()); } - FreeIPConfigStatus(ipconfig_status); - // Sort the list of ip configs by type. - std::sort(ipconfig_vector.begin(), ipconfig_vector.end()); } + return ipconfig_vector; } - return ipconfig_vector; -} -std::string NetworkLibraryImpl::GetHtmlInfo(int refresh) { - std::string output; - output.append("<html><head><title>About Network</title>"); - if (refresh > 0) - output.append("<meta http-equiv=\"refresh\" content=\"" + - base::IntToString(refresh) + "\"/>"); - output.append("</head><body>"); - if (refresh > 0) { - output.append("(Auto-refreshing page every " + - base::IntToString(refresh) + "s)"); - } else { - output.append("(To auto-refresh this page: about:network/<secs>)"); - } - - output.append("<h3>Ethernet:</h3><table border=1>"); - output.append("<tr>" + ToHtmlTableHeader(ðernet_) + "</tr>"); - output.append("<tr>" + ToHtmlTableRow(ðernet_) + "</tr>"); - - output.append("</table><h3>Wifi:</h3><table border=1>"); - for (size_t i = 0; i < wifi_networks_.size(); ++i) { - if (i == 0) - output.append("<tr>" + ToHtmlTableHeader(&wifi_networks_[i]) + "</tr>"); - output.append("<tr>" + ToHtmlTableRow(&wifi_networks_[i]) + "</tr>"); - } - - output.append("</table><h3>Cellular:</h3><table border=1>"); - for (size_t i = 0; i < cellular_networks_.size(); ++i) { - if (i == 0) - output.append("<tr>" + ToHtmlTableHeader(&cellular_networks_[i]) + + std::string GetHtmlInfo(int refresh) { + std::string output; + output.append("<html><head><title>About Network</title>"); + if (refresh > 0) + output.append("<meta http-equiv=\"refresh\" content=\"" + + base::IntToString(refresh) + "\"/>"); + output.append("</head><body>"); + if (refresh > 0) { + output.append("(Auto-refreshing page every " + + base::IntToString(refresh) + "s)"); + } else { + output.append("(To auto-refresh this page: about:network/<secs>)"); + } + + output.append("<h3>Ethernet:</h3><table border=1>"); + output.append("<tr>" + ToHtmlTableHeader(ðernet_) + "</tr>"); + output.append("<tr>" + ToHtmlTableRow(ðernet_) + "</tr>"); + + output.append("</table><h3>Wifi:</h3><table border=1>"); + for (size_t i = 0; i < wifi_networks_.size(); ++i) { + if (i == 0) + output.append("<tr>" + ToHtmlTableHeader(&wifi_networks_[i]) + "</tr>"); + output.append("<tr>" + ToHtmlTableRow(&wifi_networks_[i]) + "</tr>"); + } + + output.append("</table><h3>Cellular:</h3><table border=1>"); + for (size_t i = 0; i < cellular_networks_.size(); ++i) { + if (i == 0) + output.append("<tr>" + ToHtmlTableHeader(&cellular_networks_[i]) + + "</tr>"); + output.append("<tr>" + ToHtmlTableRow(&cellular_networks_[i]) + "</tr>"); + } + + output.append("</table><h3>Remembered Wifi:</h3><table border=1>"); + for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) { + if (i == 0) + output.append( + "<tr>" + ToHtmlTableHeader(&remembered_wifi_networks_[i]) + + "</tr>"); + output.append("<tr>" + ToHtmlTableRow(&remembered_wifi_networks_[i]) + "</tr>"); - output.append("<tr>" + ToHtmlTableRow(&cellular_networks_[i]) + "</tr>"); - } + } - output.append("</table><h3>Remembered Wifi:</h3><table border=1>"); - for (size_t i = 0; i < remembered_wifi_networks_.size(); ++i) { - if (i == 0) - output.append("<tr>" + ToHtmlTableHeader(&remembered_wifi_networks_[i]) + + output.append("</table><h3>Remembered Cellular:</h3><table border=1>"); + for (size_t i = 0; i < remembered_cellular_networks_.size(); ++i) { + if (i == 0) + output.append("<tr>" + + ToHtmlTableHeader(&remembered_cellular_networks_[i]) + "</tr>"); + output.append("<tr>" + ToHtmlTableRow(&remembered_cellular_networks_[i]) + "</tr>"); - output.append("<tr>" + ToHtmlTableRow(&remembered_wifi_networks_[i]) + - "</tr>"); - } + } - output.append("</table><h3>Remembered Cellular:</h3><table border=1>"); - for (size_t i = 0; i < remembered_cellular_networks_.size(); ++i) { - if (i == 0) - output.append("<tr>" + - ToHtmlTableHeader(&remembered_cellular_networks_[i]) + "</tr>"); - output.append("<tr>" + ToHtmlTableRow(&remembered_cellular_networks_[i]) + - "</tr>"); + output.append("</table></body></html>"); + return output; } - output.append("</table></body></html>"); - return output; -} - -// static -void NetworkLibraryImpl::NetworkStatusChangedHandler(void* object) { - NetworkLibraryImpl* network = static_cast<NetworkLibraryImpl*>(object); - DCHECK(network); - network->UpdateNetworkStatus(); -} + private: + static void NetworkStatusChangedHandler(void* object) { + NetworkLibraryImpl* network = static_cast<NetworkLibraryImpl*>(object); + DCHECK(network); + network->UpdateNetworkStatus(); + } -// static -void NetworkLibraryImpl::ParseSystem(SystemInfo* system, - EthernetNetwork* ethernet, - WifiNetworkVector* wifi_networks, - CellularNetworkVector* cellular_networks, - WifiNetworkVector* remembered_wifi_networks, - CellularNetworkVector* remembered_cellular_networks) { - DLOG(INFO) << "ParseSystem:"; - ethernet->Clear(); - for (int i = 0; i < system->service_size; i++) { - const ServiceInfo& service = system->services[i]; - DLOG(INFO) << " (" << service.type << - ") " << service.name << - " mode=" << service.mode << - " state=" << service.state << - " sec=" << service.security << - " req=" << service.passphrase_required << - " pass=" << service.passphrase << - " id=" << service.identity << - " certpath=" << service.cert_path << - " str=" << service.strength << - " fav=" << service.favorite << - " auto=" << service.auto_connect << - " error=" << service.error; - // Once a connected ethernet service is found, disregard other ethernet - // services that are also found - if (service.type == TYPE_ETHERNET && !(ethernet->connected())) - ethernet->ConfigureFromService(service); - else if (service.type == TYPE_WIFI) - wifi_networks->push_back(WifiNetwork(service)); - else if (service.type == TYPE_CELLULAR) - cellular_networks->push_back(CellularNetwork(service)); - } - DLOG(INFO) << "Remembered networks:"; - for (int i = 0; i < system->remembered_service_size; i++) { - const ServiceInfo& service = system->remembered_services[i]; - // Only serices marked as auto_connect are considered remembered networks. - // TODO(chocobo): Don't add to remembered service if currently available. - if (service.auto_connect) { + static void ParseSystem(SystemInfo* system, + EthernetNetwork* ethernet, + WifiNetworkVector* wifi_networks, + CellularNetworkVector* cellular_networks, + WifiNetworkVector* remembered_wifi_networks, + CellularNetworkVector* remembered_cellular_networks) { + DLOG(INFO) << "ParseSystem:"; + ethernet->Clear(); + for (int i = 0; i < system->service_size; i++) { + const ServiceInfo& service = system->services[i]; DLOG(INFO) << " (" << service.type << ") " << service.name << " mode=" << service.mode << + " state=" << service.state << " sec=" << service.security << + " req=" << service.passphrase_required << " pass=" << service.passphrase << " id=" << service.identity << " certpath=" << service.cert_path << - " auto=" << service.auto_connect; - if (service.type == TYPE_WIFI) - remembered_wifi_networks->push_back(WifiNetwork(service)); + " str=" << service.strength << + " fav=" << service.favorite << + " auto=" << service.auto_connect << + " error=" << service.error; + // Once a connected ethernet service is found, disregard other ethernet + // services that are also found + if (service.type == TYPE_ETHERNET && !(ethernet->connected())) + ethernet->ConfigureFromService(service); + else if (service.type == TYPE_WIFI) + wifi_networks->push_back(WifiNetwork(service)); else if (service.type == TYPE_CELLULAR) - remembered_cellular_networks->push_back(CellularNetwork(service)); + cellular_networks->push_back(CellularNetwork(service)); + } + DLOG(INFO) << "Remembered networks:"; + for (int i = 0; i < system->remembered_service_size; i++) { + const ServiceInfo& service = system->remembered_services[i]; + // Only serices marked as auto_connect are considered remembered networks. + // TODO(chocobo): Don't add to remembered service if currently available. + if (service.auto_connect) { + DLOG(INFO) << " (" << service.type << + ") " << service.name << + " mode=" << service.mode << + " sec=" << service.security << + " pass=" << service.passphrase << + " id=" << service.identity << + " certpath=" << service.cert_path << + " auto=" << service.auto_connect; + if (service.type == TYPE_WIFI) + remembered_wifi_networks->push_back(WifiNetwork(service)); + else if (service.type == TYPE_CELLULAR) + remembered_cellular_networks->push_back(CellularNetwork(service)); + } } } -} - -void NetworkLibraryImpl::Init() { - // First, get the currently available networks. This data is cached - // on the connman side, so the call should be quick. - LOG(INFO) << "Getting initial CrOS network info."; - UpdateSystemInfo(); - LOG(INFO) << "Registering for network status updates."; - // Now, register to receive updates on network status. - network_status_connection_ = MonitorNetwork(&NetworkStatusChangedHandler, - this); -} + void Init() { + // First, get the currently available networks. This data is cached + // on the connman side, so the call should be quick. + LOG(INFO) << "Getting initial CrOS network info."; + UpdateSystemInfo(); -void NetworkLibraryImpl::InitTestData() { - ethernet_.Clear(); - ethernet_.set_connected(true); - - wifi_networks_.clear(); - WifiNetwork wifi1 = WifiNetwork(); - wifi1.set_service_path("fw1"); - wifi1.set_name("Fake Wifi 1"); - wifi1.set_strength(90); - wifi1.set_connected(false); - wifi1.set_encryption(SECURITY_NONE); - wifi_networks_.push_back(wifi1); - - WifiNetwork wifi2 = WifiNetwork(); - wifi2.set_service_path("fw2"); - wifi2.set_name("Fake Wifi 2"); - wifi2.set_strength(70); - wifi2.set_connected(true); - wifi2.set_encryption(SECURITY_WEP); - wifi_networks_.push_back(wifi2); - - WifiNetwork wifi3 = WifiNetwork(); - wifi3.set_service_path("fw3"); - wifi3.set_name("Fake Wifi 3"); - wifi3.set_strength(50); - wifi3.set_connected(false); - wifi3.set_encryption(SECURITY_WEP); - wifi_networks_.push_back(wifi3); - - wifi_ = wifi2; - - cellular_networks_.clear(); - - cellular_networks_.clear(); - CellularNetwork cellular1 = CellularNetwork(); - cellular1.set_service_path("fc1"); - cellular1.set_name("Fake Cellular 1"); - cellular1.set_strength(90); - cellular1.set_connected(false); - cellular_networks_.push_back(cellular1); - - CellularNetwork cellular2 = CellularNetwork(); - cellular2.set_service_path("fc2"); - cellular2.set_name("Fake Cellular 2"); - cellular2.set_strength(70); - cellular2.set_connected(true); - cellular_networks_.push_back(cellular2); - - CellularNetwork cellular3 = CellularNetwork(); - cellular3.set_service_path("fc3"); - cellular3.set_name("Fake Cellular 3"); - cellular3.set_strength(50); - cellular3.set_connected(false); - cellular_networks_.push_back(cellular3); - - cellular_ = cellular2; - - remembered_wifi_networks_.clear(); - remembered_wifi_networks_.push_back(wifi2); - - remembered_cellular_networks_.clear(); - remembered_cellular_networks_.push_back(cellular2); - - int devices = (1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | - (1 << TYPE_CELLULAR); - available_devices_ = devices; - enabled_devices_ = devices; - connected_devices_ = devices; - offline_mode_ = false; -} + LOG(INFO) << "Registering for network status updates."; + // Now, register to receive updates on network status. + network_status_connection_ = MonitorNetwork(&NetworkStatusChangedHandler, + this); + } -void NetworkLibraryImpl::UpdateSystemInfo() { - if (CrosLibrary::Get()->EnsureLoaded()) { - UpdateNetworkStatus(); + void InitTestData() { + ethernet_.Clear(); + ethernet_.set_connected(true); + + wifi_networks_.clear(); + WifiNetwork wifi1 = WifiNetwork(); + wifi1.set_service_path("fw1"); + wifi1.set_name("Fake Wifi 1"); + wifi1.set_strength(90); + wifi1.set_connected(false); + wifi1.set_encryption(SECURITY_NONE); + wifi_networks_.push_back(wifi1); + + WifiNetwork wifi2 = WifiNetwork(); + wifi2.set_service_path("fw2"); + wifi2.set_name("Fake Wifi 2"); + wifi2.set_strength(70); + wifi2.set_connected(true); + wifi2.set_encryption(SECURITY_WEP); + wifi_networks_.push_back(wifi2); + + WifiNetwork wifi3 = WifiNetwork(); + wifi3.set_service_path("fw3"); + wifi3.set_name("Fake Wifi 3"); + wifi3.set_strength(50); + wifi3.set_connected(false); + wifi3.set_encryption(SECURITY_WEP); + wifi_networks_.push_back(wifi3); + + wifi_ = wifi2; + + cellular_networks_.clear(); + + cellular_networks_.clear(); + CellularNetwork cellular1 = CellularNetwork(); + cellular1.set_service_path("fc1"); + cellular1.set_name("Fake Cellular 1"); + cellular1.set_strength(90); + cellular1.set_connected(false); + cellular_networks_.push_back(cellular1); + + CellularNetwork cellular2 = CellularNetwork(); + cellular2.set_service_path("fc2"); + cellular2.set_name("Fake Cellular 2"); + cellular2.set_strength(70); + cellular2.set_connected(true); + cellular_networks_.push_back(cellular2); + + CellularNetwork cellular3 = CellularNetwork(); + cellular3.set_service_path("fc3"); + cellular3.set_name("Fake Cellular 3"); + cellular3.set_strength(50); + cellular3.set_connected(false); + cellular_networks_.push_back(cellular3); + + cellular_ = cellular2; + + remembered_wifi_networks_.clear(); + remembered_wifi_networks_.push_back(wifi2); + + remembered_cellular_networks_.clear(); + remembered_cellular_networks_.push_back(cellular2); + + int devices = (1 << TYPE_ETHERNET) | (1 << TYPE_WIFI) | + (1 << TYPE_CELLULAR); + available_devices_ = devices; + enabled_devices_ = devices; + connected_devices_ = devices; + offline_mode_ = false; } -} -WifiNetwork* NetworkLibraryImpl::GetPreferredNetwork() { - // First look for Google-A then look for Google. - // Only care if set to auto-connect. - WifiNetwork* wifi = GetWifiNetworkByName(kGoogleAWifi); - // If wifi found and set to not auto-connect, then ignore it. - if (wifi && !wifi->auto_connect()) - wifi = NULL; + void UpdateSystemInfo() { + if (CrosLibrary::Get()->EnsureLoaded()) { + UpdateNetworkStatus(); + } + } - if (!wifi) { - wifi = GetWifiNetworkByName(kGoogleWifi); + WifiNetwork* GetPreferredNetwork() { + // First look for Google-A then look for Google. + // Only care if set to auto-connect. + WifiNetwork* wifi = GetWifiNetworkByName(kGoogleAWifi); // If wifi found and set to not auto-connect, then ignore it. if (wifi && !wifi->auto_connect()) wifi = NULL; - } - return wifi; -} -WifiNetwork* NetworkLibraryImpl::GetWifiNetworkByName(const std::string& name) { - for (size_t i = 0; i < wifi_networks_.size(); ++i) { - if (wifi_networks_[i].name().compare(name) == 0) { - return &wifi_networks_[i]; + if (!wifi) { + wifi = GetWifiNetworkByName(kGoogleWifi); + // If wifi found and set to not auto-connect, then ignore it. + if (wifi && !wifi->auto_connect()) + wifi = NULL; } + return wifi; } - return NULL; -} -template<typename T> T* NetworkLibraryImpl::GetWirelessNetworkByPath( - std::vector<T>& networks, const std::string& path) { - typedef typename std::vector<T>::iterator iter_t; - iter_t iter = std::find_if(networks.begin(), networks.end(), - WirelessNetwork::ServicePathEq(path)); - return (iter != networks.end()) ? &(*iter) : NULL; -} - -// const version -template<typename T> const T* NetworkLibraryImpl::GetWirelessNetworkByPath( - const std::vector<T>& networks, const std::string& path) const { - typedef typename std::vector<T>::const_iterator iter_t; - iter_t iter = std::find_if(networks.begin(), networks.end(), - WirelessNetwork::ServicePathEq(path)); - return (iter != networks.end()) ? &(*iter) : NULL; -} - -void NetworkLibraryImpl::EnableNetworkDeviceType(ConnectionType device, - bool enable) { - if (!CrosLibrary::Get()->EnsureLoaded()) - return; + WifiNetwork* GetWifiNetworkByName(const std::string& name) { + for (size_t i = 0; i < wifi_networks_.size(); ++i) { + if (wifi_networks_[i].name().compare(name) == 0) { + return &wifi_networks_[i]; + } + } + return NULL; + } - // If network device is already enabled/disabled, then don't do anything. - if (enable && (enabled_devices_ & (1 << device))) { - LOG(WARNING) << "Trying to enable a device that's already enabled: " - << device; - return; + template<typename T> T* GetWirelessNetworkByPath( + std::vector<T>& networks, const std::string& path) { + typedef typename std::vector<T>::iterator iter_t; + iter_t iter = std::find_if(networks.begin(), networks.end(), + WirelessNetwork::ServicePathEq(path)); + return (iter != networks.end()) ? &(*iter) : NULL; } - if (!enable && !(enabled_devices_ & (1 << device))) { - LOG(WARNING) << "Trying to disable a device that's already disabled: " - << device; - return; + + // const version + template<typename T> const T* GetWirelessNetworkByPath( + const std::vector<T>& networks, const std::string& path) const { + typedef typename std::vector<T>::const_iterator iter_t; + iter_t iter = std::find_if(networks.begin(), networks.end(), + WirelessNetwork::ServicePathEq(path)); + return (iter != networks.end()) ? &(*iter) : NULL; } - EnableNetworkDevice(device, enable); -} + void EnableNetworkDeviceType(ConnectionType device, + bool enable) { + if (!CrosLibrary::Get()->EnsureLoaded()) + return; -void NetworkLibraryImpl::UpdateNetworkStatus() { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, - &NetworkLibraryImpl::UpdateNetworkStatus)); - return; - } + // If network device is already enabled/disabled, then don't do anything. + if (enable && (enabled_devices_ & (1 << device))) { + LOG(WARNING) << "Trying to enable a device that's already enabled: " + << device; + return; + } + if (!enable && !(enabled_devices_ & (1 << device))) { + LOG(WARNING) << "Trying to disable a device that's already disabled: " + << device; + return; + } - SystemInfo* system = GetSystemInfo(); - if (!system) - return; + EnableNetworkDevice(device, enable); + } - wifi_networks_.clear(); - cellular_networks_.clear(); - remembered_wifi_networks_.clear(); - remembered_cellular_networks_.clear(); - ParseSystem(system, ðernet_, &wifi_networks_, &cellular_networks_, - &remembered_wifi_networks_, &remembered_cellular_networks_); + void UpdateNetworkStatus() { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, + &NetworkLibraryImpl::UpdateNetworkStatus)); + return; + } - wifi_ = WifiNetwork(); - for (size_t i = 0; i < wifi_networks_.size(); i++) { - if (wifi_networks_[i].connecting_or_connected()) { - wifi_ = wifi_networks_[i]; - break; // There is only one connected or connecting wifi network. + SystemInfo* system = GetSystemInfo(); + if (!system) + return; + + wifi_networks_.clear(); + cellular_networks_.clear(); + remembered_wifi_networks_.clear(); + remembered_cellular_networks_.clear(); + ParseSystem(system, ðernet_, &wifi_networks_, &cellular_networks_, + &remembered_wifi_networks_, &remembered_cellular_networks_); + + wifi_ = WifiNetwork(); + for (size_t i = 0; i < wifi_networks_.size(); i++) { + if (wifi_networks_[i].connecting_or_connected()) { + wifi_ = wifi_networks_[i]; + break; // There is only one connected or connecting wifi network. + } } - } - cellular_ = CellularNetwork(); - for (size_t i = 0; i < cellular_networks_.size(); i++) { - if (cellular_networks_[i].connecting_or_connected()) { - cellular_ = cellular_networks_[i]; - break; // There is only one connected or connecting cellular network. + cellular_ = CellularNetwork(); + for (size_t i = 0; i < cellular_networks_.size(); i++) { + if (cellular_networks_[i].connecting_or_connected()) { + cellular_ = cellular_networks_[i]; + break; // There is only one connected or connecting cellular network. + } } - } - available_devices_ = system->available_technologies; - enabled_devices_ = system->enabled_technologies; - connected_devices_ = system->connected_technologies; - offline_mode_ = system->offline_mode; + available_devices_ = system->available_technologies; + enabled_devices_ = system->enabled_technologies; + connected_devices_ = system->connected_technologies; + offline_mode_ = system->offline_mode; - FOR_EACH_OBSERVER(Observer, observers_, NetworkChanged(this)); - FreeSystemInfo(system); -} + FOR_EACH_OBSERVER(Observer, observers_, NetworkChanged(this)); + FreeSystemInfo(system); + } -void NetworkLibraryImpl::CheckNetworkTraffic(bool download) { - // If we already have a pending upload and download notification, then - // shortcut and return. - if (traffic_type_ == (Observer::TRAFFIC_DOWNLOAD | Observer::TRAFFIC_UPLOAD)) - return; - // Figure out if we are uploading and/or downloading. We are downloading - // if download == true. We are uploading if we have upload progress. - if (download) - traffic_type_ |= Observer::TRAFFIC_DOWNLOAD; - if ((traffic_type_ & Observer::TRAFFIC_UPLOAD) == 0) { - URLRequestJobTracker::JobIterator it; - for (it = g_url_request_job_tracker.begin(); - it != g_url_request_job_tracker.end(); - ++it) { - URLRequestJob* job = *it; - if (job->GetUploadProgress() > 0) { - traffic_type_ |= Observer::TRAFFIC_UPLOAD; - break; + void CheckNetworkTraffic(bool download) { + // If we already have a pending upload and download notification, then + // shortcut and return. + if (traffic_type_ == + (Observer::TRAFFIC_DOWNLOAD | Observer::TRAFFIC_UPLOAD)) { + return; + } + // Figure out if we are uploading and/or downloading. We are downloading + // if download == true. We are uploading if we have upload progress. + if (download) + traffic_type_ |= Observer::TRAFFIC_DOWNLOAD; + if ((traffic_type_ & Observer::TRAFFIC_UPLOAD) == 0) { + URLRequestJobTracker::JobIterator it; + for (it = g_url_request_job_tracker.begin(); + it != g_url_request_job_tracker.end(); + ++it) { + URLRequestJob* job = *it; + if (job->GetUploadProgress() > 0) { + traffic_type_ |= Observer::TRAFFIC_UPLOAD; + break; + } } } + // If we have new traffic data to send out and the timer is not currently + // running, then start a new timer. + if (traffic_type_ && !timer_.IsRunning()) { + timer_.Start(base::TimeDelta::FromSeconds(kNetworkTrafficeTimerSecs), + this, + &NetworkLibraryImpl::NetworkTrafficTimerFired); + } } - // If we have new traffic data to send out and the timer is not currently - // running, then start a new timer. - if (traffic_type_ && !timer_.IsRunning()) { - timer_.Start(base::TimeDelta::FromSeconds(kNetworkTrafficeTimerSecs), this, - &NetworkLibraryImpl::NetworkTrafficTimerFired); + + void NetworkTrafficTimerFired() { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, &NetworkLibraryImpl::NotifyNetworkTraffic, + traffic_type_)); + // Reset traffic type so that we don't send the same data next time. + traffic_type_ = 0; } -} -void NetworkLibraryImpl:: NetworkTrafficTimerFired() { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &NetworkLibraryImpl::NotifyNetworkTraffic, - traffic_type_)); - // Reset traffic type so that we don't send the same data next time. - traffic_type_ = 0; -} + void NotifyNetworkTraffic(int traffic_type) { + FOR_EACH_OBSERVER(Observer, observers_, NetworkTraffic(this, traffic_type)); + } -void NetworkLibraryImpl::NotifyNetworkTraffic(int traffic_type) { - FOR_EACH_OBSERVER(Observer, observers_, NetworkTraffic(this, traffic_type)); -} + ObserverList<Observer> observers_; -bool NetworkLibraryImpl::Connected() const { - return ethernet_connected() || wifi_connected() || cellular_connected(); -} + // The amount of time to wait between each NetworkTraffic notifications. + static const int kNetworkTrafficeTimerSecs = 1; -bool NetworkLibraryImpl::Connecting() const { - return ethernet_connecting() || wifi_connecting() || cellular_connecting(); -} + // Timer for sending NetworkTraffic notification every + // kNetworkTrafficeTimerSecs seconds. + base::OneShotTimer<NetworkLibraryImpl> timer_; -const std::string& NetworkLibraryImpl::IPAddress() const { - // Returns highest priority IP address. - if (ethernet_connected()) - return ethernet_.ip_address(); - if (wifi_connected()) - return wifi_.ip_address(); - if (cellular_connected()) - return cellular_.ip_address(); - return ethernet_.ip_address(); + // The current traffic type that will be sent out for the next NetworkTraffic + // notification. This is a bitfield of TrafficTypeMasks. + int traffic_type_; + + // The network status connection for monitoring network status changes. + MonitorNetworkConnection network_status_connection_; + + // The ethernet network. + EthernetNetwork ethernet_; + + // The list of available wifi networks. + WifiNetworkVector wifi_networks_; + + // The current connected (or connecting) wifi network. + WifiNetwork wifi_; + + // The remembered wifi networks. + WifiNetworkVector remembered_wifi_networks_; + + // The list of available cellular networks. + CellularNetworkVector cellular_networks_; + + // The current connected (or connecting) cellular network. + CellularNetwork cellular_; + + // The remembered cellular networks. + CellularNetworkVector remembered_cellular_networks_; + + // The current available network devices. Bitwise flag of ConnectionTypes. + int available_devices_; + + // The current enabled network devices. Bitwise flag of ConnectionTypes. + int enabled_devices_; + + // The current connected network devices. Bitwise flag of ConnectionTypes. + int connected_devices_; + + bool offline_mode_; + + DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl); +}; + +class NetworkLibraryStubImpl : public NetworkLibrary { + public: + NetworkLibraryStubImpl() : ip_address_("1.1.1.1") {} + ~NetworkLibraryStubImpl() {} + void OnJobAdded(URLRequestJob* job) {} + void OnJobRemoved(URLRequestJob* job) {} + void OnJobDone(URLRequestJob* job, const URLRequestStatus& status) {} + void OnJobRedirect( + URLRequestJob* job, const GURL& location, int status_code) {} + void OnBytesRead(URLRequestJob* job, int byte_count) {} + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} + virtual const EthernetNetwork& ethernet_network() const { + return ethernet_; + } + virtual bool ethernet_connecting() const { return false; } + virtual bool ethernet_connected() const { return true; } + virtual const std::string& wifi_name() const { return EmptyString(); } + virtual bool wifi_connecting() const { return false; } + virtual bool wifi_connected() const { return false; } + virtual int wifi_strength() const { return 0; } + + virtual const std::string& cellular_name() const { return EmptyString(); } + virtual bool cellular_connecting() const { return false; } + virtual bool cellular_connected() const { return false; } + virtual int cellular_strength() const { return false; } + + bool Connected() const { return true; } + bool Connecting() const { return false; } + const std::string& IPAddress() const { return ip_address_; } + virtual const WifiNetworkVector& wifi_networks() const { + return wifi_networks_; + } + virtual const WifiNetworkVector& remembered_wifi_networks() const { + return wifi_networks_; + } + virtual const CellularNetworkVector& cellular_networks() const { + return cellular_networks_; + } + virtual const CellularNetworkVector& remembered_cellular_networks() const { + return cellular_networks_; + } + + ///////////////////////////////////////////////////////////////////////////// + + bool FindWifiNetworkByPath( + const std::string& path, WifiNetwork* result) const { return false; } + bool FindCellularNetworkByPath( + const std::string& path, CellularNetwork* result) const { return false; } + void RequestWifiScan() {} + bool GetWifiAccessPoints(WifiAccessPointVector* result) { return false; } + bool ConnectToPreferredNetworkIfAvailable() { return false; } + bool PreferredNetworkConnected() { return false; } + bool PreferredNetworkFailed() { return false; } + void ConnectToWifiNetwork(WifiNetwork network, + const std::string& password, + const std::string& identity, + const std::string& certpath) {} + void ConnectToWifiNetwork(const std::string& ssid, + const std::string& password, + const std::string& identity, + const std::string& certpath, + bool auto_connect) {} + void ConnectToCellularNetwork(CellularNetwork network) {} + void DisconnectFromWirelessNetwork(const WirelessNetwork& network) {} + void SaveCellularNetwork(const CellularNetwork& network) {} + void SaveWifiNetwork(const WifiNetwork& network) {} + void ForgetWirelessNetwork(const std::string& service_path) {} + virtual bool ethernet_available() const { return true; } + virtual bool wifi_available() const { return false; } + virtual bool cellular_available() const { return false; } + virtual bool ethernet_enabled() const { return true; } + virtual bool wifi_enabled() const { return false; } + virtual bool cellular_enabled() const { return false; } + virtual bool offline_mode() const { return false; } + void EnableEthernetNetworkDevice(bool enable) {} + void EnableWifiNetworkDevice(bool enable) {} + void EnableCellularNetworkDevice(bool enable) {} + void EnableOfflineMode(bool enable) {} + NetworkIPConfigVector GetIPConfigs(const std::string& device_path) { + return NetworkIPConfigVector(); + } + std::string GetHtmlInfo(int refresh) { return std::string(); } + void UpdateSystemInfo() {} + + private: + std::string ip_address_; + EthernetNetwork ethernet_; + WifiNetworkVector wifi_networks_; + CellularNetworkVector cellular_networks_; +}; + +// static +NetworkLibrary* NetworkLibrary::GetImpl(bool stub) { + if (stub) + return new NetworkLibraryStubImpl(); + else + return new NetworkLibraryImpl(); } } // namespace chromeos + +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::NetworkLibraryImpl); diff --git a/chrome/browser/chromeos/cros/network_library.h b/chrome/browser/chromeos/cros/network_library.h index 0a7e5a2..81b287e 100644 --- a/chrome/browser/chromeos/cros/network_library.h +++ b/chrome/browser/chromeos/cros/network_library.h @@ -373,231 +373,9 @@ class NetworkLibrary { // Fetches debug network info for display in about:network. // The page will have a meta refresh of |refresh| seconds if |refresh| > 0. virtual std::string GetHtmlInfo(int refresh) = 0; -}; - -// This class handles the interaction with the ChromeOS network library APIs. -// Classes can add themselves as observers. Users can get an instance of this -// library class like this: NetworkLibrary::Get() -class NetworkLibraryImpl : public NetworkLibrary, - public URLRequestJobTracker::JobObserver { - public: - NetworkLibraryImpl(); - virtual ~NetworkLibraryImpl(); - - // URLRequestJobTracker::JobObserver methods (called on the IO thread): - virtual void OnJobAdded(URLRequestJob* job); - virtual void OnJobRemoved(URLRequestJob* job); - virtual void OnJobDone(URLRequestJob* job, const URLRequestStatus& status); - virtual void OnJobRedirect(URLRequestJob* job, const GURL& location, - int status_code); - virtual void OnBytesRead(URLRequestJob* job, int byte_count); - - // NetworkLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - - virtual const EthernetNetwork& ethernet_network() const { return ethernet_; } - virtual bool ethernet_connecting() const { return ethernet_.connecting(); } - virtual bool ethernet_connected() const { return ethernet_.connected(); } - - virtual const std::string& wifi_name() const { return wifi_.name(); } - virtual bool wifi_connecting() const { return wifi_.connecting(); } - virtual bool wifi_connected() const { return wifi_.connected(); } - virtual int wifi_strength() const { return wifi_.strength(); } - - virtual const std::string& cellular_name() const { return cellular_.name(); } - virtual bool cellular_connecting() const { return cellular_.connecting(); } - virtual bool cellular_connected() const { return cellular_.connected(); } - virtual int cellular_strength() const { return cellular_.strength(); } - - virtual bool Connected() const; - virtual bool Connecting() const; - virtual const std::string& IPAddress() const; - - virtual const WifiNetworkVector& wifi_networks() const { - return wifi_networks_; - } - - virtual const WifiNetworkVector& remembered_wifi_networks() const { - return remembered_wifi_networks_; - } - - virtual const CellularNetworkVector& cellular_networks() const { - return cellular_networks_; - } - - virtual const CellularNetworkVector& remembered_cellular_networks() const { - return remembered_cellular_networks_; - } - - virtual bool FindWifiNetworkByPath(const std::string& path, - WifiNetwork* network) const; - virtual bool FindCellularNetworkByPath(const std::string& path, - CellularNetwork* network) const; - - virtual void RequestWifiScan(); - virtual bool GetWifiAccessPoints(WifiAccessPointVector* result); - virtual bool ConnectToPreferredNetworkIfAvailable(); - virtual bool PreferredNetworkConnected(); - virtual bool PreferredNetworkFailed(); - virtual void ConnectToWifiNetwork(WifiNetwork network, - const std::string& password, - const std::string& identity, - const std::string& certpath); - virtual void ConnectToWifiNetwork(const std::string& ssid, - const std::string& password, - const std::string& identity, - const std::string& certpath, - bool auto_connect); - virtual void ConnectToCellularNetwork(CellularNetwork network); - virtual void DisconnectFromWirelessNetwork(const WirelessNetwork& network); - virtual void SaveCellularNetwork(const CellularNetwork& network); - virtual void SaveWifiNetwork(const WifiNetwork& network); - virtual void ForgetWirelessNetwork(const std::string& service_path); - - virtual bool ethernet_available() const { - return available_devices_ & (1 << TYPE_ETHERNET); - } - virtual bool wifi_available() const { - return available_devices_ & (1 << TYPE_WIFI); - } - virtual bool cellular_available() const { - return available_devices_ & (1 << TYPE_CELLULAR); - } - - virtual bool ethernet_enabled() const { - return enabled_devices_ & (1 << TYPE_ETHERNET); - } - virtual bool wifi_enabled() const { - return enabled_devices_ & (1 << TYPE_WIFI); - } - virtual bool cellular_enabled() const { - return enabled_devices_ & (1 << TYPE_CELLULAR); - } - - virtual bool offline_mode() const { return offline_mode_; } - - virtual void EnableEthernetNetworkDevice(bool enable); - virtual void EnableWifiNetworkDevice(bool enable); - virtual void EnableCellularNetworkDevice(bool enable); - virtual void EnableOfflineMode(bool enable); - virtual NetworkIPConfigVector GetIPConfigs(const std::string& device_path); - virtual std::string GetHtmlInfo(int refresh); - - virtual void UpdateSystemInfo(); - - private: - - // This method is called when there's a change in network status. - // This method is called on a background thread. - static void NetworkStatusChangedHandler(void* object); - - // This parses SystemInfo into: - // - an EthernetNetwork - // - a WifiNetworkVector of wifi networks - // - a CellularNetworkVector of cellular networks. - // - a WifiNetworkVector of remembered wifi networks - // - a CellularNetworkVector of remembered cellular networks. - static void ParseSystem(SystemInfo* system, - EthernetNetwork* ethernet, - WifiNetworkVector* wifi_networks, - CellularNetworkVector* ceullular_networks, - WifiNetworkVector* remembered_wifi_networks, - CellularNetworkVector* remembered_ceullular_networks); - - // This methods loads the initial list of networks on startup and starts the - // monitoring of network changes. - void Init(); - // Initialize with test data. - void InitTestData(); - - // Returns the preferred wifi network. - WifiNetwork* GetPreferredNetwork(); - - // Gets the WifiNetwork with the given name. Returns NULL if not found. - // Only used by GetPreferredNetwork() to lookup "Google" and "GoogleA" (hack) - WifiNetwork* GetWifiNetworkByName(const std::string& name); - - // Gets the WirelessNetwork (WifiNetwork or CellularNetwork) by path - template<typename T> - T* GetWirelessNetworkByPath(std::vector<T>& networks, - const std::string& path); - template<typename T> - const T* GetWirelessNetworkByPath(const std::vector<T>& networks, - const std::string& path) const; - - // Enables/disables the specified network device. - void EnableNetworkDeviceType(ConnectionType device, bool enable); - - // Update the cached network status. - // This will notify all the Observers. - void UpdateNetworkStatus(); - - // Checks network traffic to see if there is any uploading. - // If there is download traffic, then true is passed in for download. - // If there is network traffic then start timer that invokes - // NetworkTrafficTimerFired. - void CheckNetworkTraffic(bool download); - - // Called when the timer fires and we need to send out NetworkTraffic - // notifications. - void NetworkTrafficTimerFired(); - - // This is a helper method to notify the observers on the UI thread. - void NotifyNetworkTraffic(int traffic_type); - - // This will notify all obeservers on the UI thread. - void NotifyObservers(); - - ObserverList<Observer> observers_; - - // The amount of time to wait between each NetworkTraffic notifications. - static const int kNetworkTrafficeTimerSecs; - - // Timer for sending NetworkTraffic notification every - // kNetworkTrafficeTimerSecs seconds. - base::OneShotTimer<NetworkLibraryImpl> timer_; - - // The current traffic type that will be sent out for the next NetworkTraffic - // notification. This is a bitfield of TrafficTypeMasks. - int traffic_type_; - - // The network status connection for monitoring network status changes. - MonitorNetworkConnection network_status_connection_; - - // The ethernet network. - EthernetNetwork ethernet_; - - // The list of available wifi networks. - WifiNetworkVector wifi_networks_; - - // The current connected (or connecting) wifi network. - WifiNetwork wifi_; - - // The remembered wifi networks. - WifiNetworkVector remembered_wifi_networks_; - - // The list of available cellular networks. - CellularNetworkVector cellular_networks_; - - // The current connected (or connecting) cellular network. - CellularNetwork cellular_; - - // The remembered cellular networks. - CellularNetworkVector remembered_cellular_networks_; - - // The current available network devices. Bitwise flag of ConnectionTypes. - int available_devices_; - - // The current enabled network devices. Bitwise flag of ConnectionTypes. - int enabled_devices_; - - // The current connected network devices. Bitwise flag of ConnectionTypes. - int connected_devices_; - - bool offline_mode_; - DISALLOW_COPY_AND_ASSIGN(NetworkLibraryImpl); + // Get library implementation. + static NetworkLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/power_library.cc b/chrome/browser/chromeos/cros/power_library.cc index 42978aa..220cd4e 100644 --- a/chrome/browser/chromeos/cros/power_library.cc +++ b/chrome/browser/chromeos/cros/power_library.cc @@ -9,87 +9,129 @@ #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl); - namespace chromeos { -PowerLibraryImpl::PowerLibraryImpl() - : power_status_connection_(NULL), - status_(chromeos::PowerStatus()) { - if (CrosLibrary::Get()->EnsureLoaded()) { - Init(); +class PowerLibraryImpl : public PowerLibrary { + public: + PowerLibraryImpl() + : power_status_connection_(NULL), + status_(chromeos::PowerStatus()) { + if (CrosLibrary::Get()->EnsureLoaded()) { + Init(); + } } -} -PowerLibraryImpl::~PowerLibraryImpl() { - if (power_status_connection_) { - chromeos::DisconnectPowerStatus(power_status_connection_); + ~PowerLibraryImpl() { + if (power_status_connection_) { + chromeos::DisconnectPowerStatus(power_status_connection_); + } } -} -void PowerLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void PowerLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -bool PowerLibraryImpl::line_power_on() const { - return status_.line_power_on; -} + bool line_power_on() const { + return status_.line_power_on; + } -bool PowerLibraryImpl::battery_is_present() const { - return status_.battery_is_present; -} + bool battery_is_present() const { + return status_.battery_is_present; + } -bool PowerLibraryImpl::battery_fully_charged() const { - return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED; -} + bool battery_fully_charged() const { + return status_.battery_state == chromeos::BATTERY_STATE_FULLY_CHARGED; + } -double PowerLibraryImpl::battery_percentage() const { - return status_.battery_percentage; -} + double battery_percentage() const { + return status_.battery_percentage; + } -base::TimeDelta PowerLibraryImpl::battery_time_to_empty() const { - return base::TimeDelta::FromSeconds(status_.battery_time_to_empty); -} + base::TimeDelta battery_time_to_empty() const { + return base::TimeDelta::FromSeconds(status_.battery_time_to_empty); + } -base::TimeDelta PowerLibraryImpl::battery_time_to_full() const { - return base::TimeDelta::FromSeconds(status_.battery_time_to_full); -} + base::TimeDelta battery_time_to_full() const { + return base::TimeDelta::FromSeconds(status_.battery_time_to_full); + } -// static -void PowerLibraryImpl::PowerStatusChangedHandler(void* object, - const chromeos::PowerStatus& status) { - PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object); - power->UpdatePowerStatus(status); -} + private: + static void PowerStatusChangedHandler(void* object, + const chromeos::PowerStatus& status) { + PowerLibraryImpl* power = static_cast<PowerLibraryImpl*>(object); + power->UpdatePowerStatus(status); + } -void PowerLibraryImpl::Init() { - power_status_connection_ = chromeos::MonitorPowerStatus( - &PowerStatusChangedHandler, this); -} + void Init() { + power_status_connection_ = chromeos::MonitorPowerStatus( + &PowerStatusChangedHandler, this); + } -void PowerLibraryImpl::UpdatePowerStatus(const chromeos::PowerStatus& status) { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &PowerLibraryImpl::UpdatePowerStatus, status)); - return; + void UpdatePowerStatus(const chromeos::PowerStatus& status) { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod( + this, &PowerLibraryImpl::UpdatePowerStatus, status)); + return; + } + + DLOG(INFO) << "Power" << + " lpo=" << status.line_power_on << + " sta=" << status.battery_state << + " per=" << status.battery_percentage << + " tte=" << status.battery_time_to_empty << + " ttf=" << status.battery_time_to_full; + status_ = status; + FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this)); } - DLOG(INFO) << "Power" << - " lpo=" << status.line_power_on << - " sta=" << status.battery_state << - " per=" << status.battery_percentage << - " tte=" << status.battery_time_to_empty << - " ttf=" << status.battery_time_to_full; - status_ = status; - FOR_EACH_OBSERVER(Observer, observers_, PowerChanged(this)); + ObserverList<Observer> observers_; + + // A reference to the battery power api, to allow callbacks when the battery + // status changes. + chromeos::PowerStatusConnection power_status_connection_; + + // The latest power status. + chromeos::PowerStatus status_; + + DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl); +}; + +class PowerLibraryStubImpl : public PowerLibrary { + public: + PowerLibraryStubImpl() {} + ~PowerLibraryStubImpl() {} + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} + bool line_power_on() const { return false; } + bool battery_is_present() const { return false; } + bool battery_fully_charged() const { return false; } + double battery_percentage() const { return false; } + base::TimeDelta battery_time_to_empty() const { + return base::TimeDelta::FromSeconds(0); + } + base::TimeDelta battery_time_to_full() const { + return base::TimeDelta::FromSeconds(0); + } +}; + +// static +PowerLibrary* PowerLibrary::GetImpl(bool stub) { + if (stub) + return new PowerLibraryStubImpl(); + else + return new PowerLibraryImpl(); } } // namespace chromeos + +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::PowerLibraryImpl); + diff --git a/chrome/browser/chromeos/cros/power_library.h b/chrome/browser/chromeos/cros/power_library.h index 81c00cc..7116629 100644 --- a/chrome/browser/chromeos/cros/power_library.h +++ b/chrome/browser/chromeos/cros/power_library.h @@ -42,63 +42,9 @@ class PowerLibrary { // The amount of time until battery is full. virtual base::TimeDelta battery_time_to_full() const = 0; -}; - - -// This class handles the interaction with the ChromeOS power library APIs. -// Classes can add themselves as observers. Users can get an instance of this -// library class like this: PowerLibrary::Get() -class PowerLibraryImpl : public PowerLibrary { - public: - PowerLibraryImpl(); - virtual ~PowerLibraryImpl(); - - // PowerLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - - // Whether or not the line power is connected. - virtual bool line_power_on() const; - - // Whether or not the battery is fully charged.. - virtual bool battery_fully_charged() const; - - // The percentage (0-100) of remaining battery. - virtual double battery_percentage() const; - - // Whether there is a battery present. - virtual bool battery_is_present() const; - - // The amount of time until battery is empty. - virtual base::TimeDelta battery_time_to_empty() const; - - // The amount of time until battery is full. - virtual base::TimeDelta battery_time_to_full() const; - - private: - - // This method is called when there's a change in power status. - // This method is called on a background thread. - static void PowerStatusChangedHandler(void* object, - const chromeos::PowerStatus& status); - - // This methods starts the monitoring of power changes. - void Init(); - - // Called by the handler to update the power status. - // This will notify all the Observers. - void UpdatePowerStatus(const chromeos::PowerStatus& status); - - ObserverList<Observer> observers_; - - // A reference to the battery power api, to allow callbacks when the battery - // status changes. - chromeos::PowerStatusConnection power_status_connection_; - - // The latest power status. - chromeos::PowerStatus status_; - DISALLOW_COPY_AND_ASSIGN(PowerLibraryImpl); + // Get library implementation. + static PowerLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/screen_lock_library.cc b/chrome/browser/chromeos/cros/screen_lock_library.cc index 731ec43..0115683 100644 --- a/chrome/browser/chromeos/cros/screen_lock_library.cc +++ b/chrome/browser/chromeos/cros/screen_lock_library.cc @@ -9,135 +9,170 @@ #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl); - namespace chromeos { -ScreenLockLibraryImpl::ScreenLockLibraryImpl() { - if (CrosLibrary::Get()->EnsureLoaded()) { - Init(); +// This class handles the interaction with the ChromeOS screen lock APIs. +class ScreenLockLibraryImpl : public ScreenLockLibrary { + public: + ScreenLockLibraryImpl() { + if (CrosLibrary::Get()->EnsureLoaded()) { + Init(); + } } -} -ScreenLockLibraryImpl::~ScreenLockLibraryImpl() { - if (screen_lock_connection_) { - chromeos::DisconnectScreenLock(screen_lock_connection_); + ~ScreenLockLibraryImpl() { + if (screen_lock_connection_) { + chromeos::DisconnectScreenLock(screen_lock_connection_); + } } -} -void ScreenLockLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void ScreenLockLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -void ScreenLockLibraryImpl::NotifyScreenLockRequested() { - // Make sure we run on IO thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { - ChromeThread::PostTask( - ChromeThread::IO, FROM_HERE, - NewRunnableMethod(this, - &ScreenLockLibraryImpl::NotifyScreenLockRequested)); - return; + void NotifyScreenLockRequested() { + // Make sure we run on IO thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { + ChromeThread::PostTask( + ChromeThread::IO, FROM_HERE, + NewRunnableMethod( + this, + &ScreenLockLibraryImpl::NotifyScreenLockRequested)); + return; + } + chromeos::NotifyScreenLockRequested(); } - chromeos::NotifyScreenLockRequested(); -} -void ScreenLockLibraryImpl::NotifyScreenLockCompleted() { - // Make sure we run on IO thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { - ChromeThread::PostTask( - ChromeThread::IO, FROM_HERE, - NewRunnableMethod(this, - &ScreenLockLibraryImpl::NotifyScreenLockCompleted)); - return; + void NotifyScreenLockCompleted() { + // Make sure we run on IO thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { + ChromeThread::PostTask( + ChromeThread::IO, FROM_HERE, + NewRunnableMethod( + this, + &ScreenLockLibraryImpl::NotifyScreenLockCompleted)); + return; + } + chromeos::NotifyScreenLockCompleted(); } - chromeos::NotifyScreenLockCompleted(); -} -void ScreenLockLibraryImpl::NotifyScreenUnlockRequested() { - // Make sure we run on IO thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { - ChromeThread::PostTask( - ChromeThread::IO, FROM_HERE, - NewRunnableMethod(this, - &ScreenLockLibraryImpl::NotifyScreenUnlockRequested)); - return; + void NotifyScreenUnlockRequested() { + // Make sure we run on IO thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { + ChromeThread::PostTask( + ChromeThread::IO, FROM_HERE, + NewRunnableMethod( + this, + &ScreenLockLibraryImpl::NotifyScreenUnlockRequested)); + return; + } + chromeos::NotifyScreenUnlockRequested(); } - chromeos::NotifyScreenUnlockRequested(); -} -void ScreenLockLibraryImpl::NotifyScreenUnlockCompleted() { - // Make sure we run on IO thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { - ChromeThread::PostTask( - ChromeThread::IO, FROM_HERE, - NewRunnableMethod(this, - &ScreenLockLibraryImpl::NotifyScreenUnlockCompleted)); - return; + void NotifyScreenUnlockCompleted() { + // Make sure we run on IO thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::IO)) { + ChromeThread::PostTask( + ChromeThread::IO, FROM_HERE, + NewRunnableMethod( + this, + &ScreenLockLibraryImpl::NotifyScreenUnlockCompleted)); + return; + } + chromeos::NotifyScreenUnlockCompleted(); } - chromeos::NotifyScreenUnlockCompleted(); -} -void ScreenLockLibraryImpl::Init() { - screen_lock_connection_ = chromeos::MonitorScreenLock( - &ScreenLockedHandler, this); -} + private: + void Init() { + screen_lock_connection_ = chromeos::MonitorScreenLock( + &ScreenLockedHandler, this); + } -void ScreenLockLibraryImpl::LockScreen() { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen)); - return; + void LockScreen() { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, &ScreenLockLibraryImpl::LockScreen)); + return; + } + FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this)); } - FOR_EACH_OBSERVER(Observer, observers_, LockScreen(this)); -} -void ScreenLockLibraryImpl::UnlockScreen() { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen)); - return; + void UnlockScreen() { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreen)); + return; + } + FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this)); } - FOR_EACH_OBSERVER(Observer, observers_, UnlockScreen(this)); -} -void ScreenLockLibraryImpl::UnlockScreenFailed() { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed)); - return; + void UnlockScreenFailed() { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, &ScreenLockLibraryImpl::UnlockScreenFailed)); + return; + } + FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this)); } - FOR_EACH_OBSERVER(Observer, observers_, UnlockScreenFailed(this)); -} -// static -void ScreenLockLibraryImpl::ScreenLockedHandler(void* object, - ScreenLockEvent event) { - ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object); - switch (event) { - case chromeos::LockScreen: - self->LockScreen(); - break; - case chromeos::UnlockScreen: - self->UnlockScreen(); - break; - case chromeos::UnlockScreenFailed: - self->UnlockScreenFailed(); - break; - default: - NOTREACHED(); + static void ScreenLockedHandler(void* object, ScreenLockEvent event) { + ScreenLockLibraryImpl* self = static_cast<ScreenLockLibraryImpl*>(object); + switch (event) { + case chromeos::LockScreen: + self->LockScreen(); + break; + case chromeos::UnlockScreen: + self->UnlockScreen(); + break; + case chromeos::UnlockScreenFailed: + self->UnlockScreenFailed(); + break; + default: + NOTREACHED(); + } } + + ObserverList<Observer> observers_; + + // A reference to the screen lock api + chromeos::ScreenLockConnection screen_lock_connection_; + + DISALLOW_COPY_AND_ASSIGN(ScreenLockLibraryImpl); +}; + +class ScreenLockLibraryStubImpl : public ScreenLockLibrary { + public: + ScreenLockLibraryStubImpl() {} + ~ScreenLockLibraryStubImpl() {} + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} + void NotifyScreenLockRequested() {} + void NotifyScreenLockCompleted() {} + void NotifyScreenUnlockRequested() {} + void NotifyScreenUnlockCompleted() {} +}; + +// static +ScreenLockLibrary* ScreenLockLibrary::GetImpl(bool stub) { + if (stub) + return new ScreenLockLibraryStubImpl(); + else + return new ScreenLockLibraryImpl(); } } // namespace chromeos + +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::ScreenLockLibraryImpl); + diff --git a/chrome/browser/chromeos/cros/screen_lock_library.h b/chrome/browser/chromeos/cros/screen_lock_library.h index a544c44..f6206e0 100644 --- a/chrome/browser/chromeos/cros/screen_lock_library.h +++ b/chrome/browser/chromeos/cros/screen_lock_library.h @@ -35,48 +35,9 @@ class ScreenLockLibrary { virtual void NotifyScreenUnlockRequested() = 0; // Notifies PowerManager that screen is unlocked. virtual void NotifyScreenUnlockCompleted() = 0; -}; - -// This class handles the interaction with the ChromeOS screen lock APIs. -class ScreenLockLibraryImpl : public ScreenLockLibrary { - public: - ScreenLockLibraryImpl(); - virtual ~ScreenLockLibraryImpl(); - - // ScreenLockLibrary implementations: - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - virtual void NotifyScreenLockRequested(); - virtual void NotifyScreenLockCompleted(); - virtual void NotifyScreenUnlockRequested(); - virtual void NotifyScreenUnlockCompleted(); - - private: - // This method is called when PowerManager requests to lock the screen. - // This method is called on a background thread. - static void ScreenLockedHandler(void* object, ScreenLockEvent event); - - // This methods starts the monitoring of screen lock request. - void Init(); - - // Called by the handler to notify the screen lock request from - // SessionManager. - void LockScreen(); - - // Called by the handler to notify the screen unlock request from - // SessionManager. - void UnlockScreen(); - - // Called by the handler to notify the screen unlock request has been - // failed. - void UnlockScreenFailed(); - - ObserverList<Observer> observers_; - - // A reference to the screen lock api - chromeos::ScreenLockConnection screen_lock_connection_; - DISALLOW_COPY_AND_ASSIGN(ScreenLockLibraryImpl); + // Get library implementation. + static ScreenLockLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/speech_synthesis_library.cc b/chrome/browser/chromeos/cros/speech_synthesis_library.cc index 10194ee..0325c1f 100644 --- a/chrome/browser/chromeos/cros/speech_synthesis_library.cc +++ b/chrome/browser/chromeos/cros/speech_synthesis_library.cc @@ -11,24 +11,55 @@ namespace chromeos { -bool SpeechSynthesisLibraryImpl::Speak(const char* text) { - return chromeos::Speak(text); -} +class SpeechSynthesisLibraryImpl : public SpeechSynthesisLibrary { + public: + SpeechSynthesisLibraryImpl() {} + virtual ~SpeechSynthesisLibraryImpl() {} -bool SpeechSynthesisLibraryImpl::SetSpeakProperties(const char* props) { - return chromeos::SetSpeakProperties(props); -} + bool Speak(const char* text) { + return chromeos::Speak(text); + } -bool SpeechSynthesisLibraryImpl::StopSpeaking() { - return chromeos::StopSpeaking(); -} + bool SetSpeakProperties(const char* props) { + return chromeos::SetSpeakProperties(props); + } -bool SpeechSynthesisLibraryImpl::IsSpeaking() { - return chromeos::IsSpeaking(); -} + bool StopSpeaking() { + return chromeos::StopSpeaking(); + } + + bool IsSpeaking() { + return chromeos::IsSpeaking(); + } + + void InitTts(InitStatusCallback callback) { + chromeos::InitTts(callback); + } + + private: + DISALLOW_COPY_AND_ASSIGN(SpeechSynthesisLibraryImpl); +}; + +class SpeechSynthesisLibraryStubImpl : public SpeechSynthesisLibrary { + public: + SpeechSynthesisLibraryStubImpl() {} + virtual ~SpeechSynthesisLibraryStubImpl() {} + bool Speak(const char* text) { return true; } + bool SetSpeakProperties(const char* props) { return true; } + bool StopSpeaking() { return true; } + bool IsSpeaking() { return false; } + void InitTts(InitStatusCallback callback) {} + + private: + DISALLOW_COPY_AND_ASSIGN(SpeechSynthesisLibraryStubImpl); +}; -void SpeechSynthesisLibraryImpl::InitTts(InitStatusCallback callback) { - chromeos::InitTts(callback); +// static +SpeechSynthesisLibrary* SpeechSynthesisLibrary::GetImpl(bool stub) { + if (stub) + return new SpeechSynthesisLibraryStubImpl(); + else + return new SpeechSynthesisLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/speech_synthesis_library.h b/chrome/browser/chromeos/cros/speech_synthesis_library.h index e6d97e4..adf3b38 100644 --- a/chrome/browser/chromeos/cros/speech_synthesis_library.h +++ b/chrome/browser/chromeos/cros/speech_synthesis_library.h @@ -27,23 +27,9 @@ class SpeechSynthesisLibrary { // Starts the speech synthesis service and indicates through a callback if // it started successfully. virtual void InitTts(InitStatusCallback) = 0; -}; -// This class handles the interaction with the ChromeOS login library APIs. -class SpeechSynthesisLibraryImpl : public SpeechSynthesisLibrary { - public: - SpeechSynthesisLibraryImpl() {} - virtual ~SpeechSynthesisLibraryImpl() {} - - // SpeechSynthesisLibrary overrides. - virtual bool Speak(const char* text); - virtual bool SetSpeakProperties(const char* props); - virtual bool StopSpeaking(); - virtual bool IsSpeaking(); - virtual void InitTts(InitStatusCallback); - - private: - DISALLOW_COPY_AND_ASSIGN(SpeechSynthesisLibraryImpl); + // Get library implementation. + static SpeechSynthesisLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/synaptics_library.cc b/chrome/browser/chromeos/cros/synaptics_library.cc index 462be76..c7413df 100644 --- a/chrome/browser/chromeos/cros/synaptics_library.cc +++ b/chrome/browser/chromeos/cros/synaptics_library.cc @@ -9,29 +9,61 @@ #include "chrome/browser/chromeos/cros/cros_library.h" namespace chromeos { +// This class handles the interaction with the ChromeOS synaptics library APIs. +// Users can get an instance of this library class like this: +// SynapticsLibrary::Get() +// For a list of SynapticsPrameters, see chromeos_synaptics.h +// in third_party/cros or /usr/include/cros +class SynapticsLibraryImpl : public SynapticsLibrary { + public: + SynapticsLibraryImpl() {} + virtual ~SynapticsLibraryImpl() {} -void SynapticsLibraryImpl::SetBoolParameter(SynapticsParameter param, - bool value) { - SetParameter(param, value ? 1 : 0); -} + void SetBoolParameter(SynapticsParameter param, bool value) { + SetParameter(param, value ? 1 : 0); + } -void SynapticsLibraryImpl::SetRangeParameter(SynapticsParameter param, - int value) { - if (value < 1) - value = 1; - if (value > 10) - value = 10; - SetParameter(param, value); -} + void SetRangeParameter(SynapticsParameter param, int value) { + if (value < 1) + value = 1; + if (value > 10) + value = 10; + SetParameter(param, value); + } -void SynapticsLibraryImpl::SetParameter(SynapticsParameter param, int value) { - if (CrosLibrary::Get()->EnsureLoaded()) { - // This calls SetSynapticsParameter in the cros library which is - // potentially time consuming. So we run this on the FILE thread. - ChromeThread::PostTask( - ChromeThread::FILE, FROM_HERE, - NewRunnableFunction(&SetSynapticsParameter, param, value)); + private: + // This helper methods calls into the libcros library to set the parameter. + // This call is run on the FILE thread. + void SetParameter(SynapticsParameter param, int value) { + if (CrosLibrary::Get()->EnsureLoaded()) { + // This calls SetSynapticsParameter in the cros library which is + // potentially time consuming. So we run this on the FILE thread. + ChromeThread::PostTask( + ChromeThread::FILE, FROM_HERE, + NewRunnableFunction(&SetSynapticsParameter, param, value)); + } } + + DISALLOW_COPY_AND_ASSIGN(SynapticsLibraryImpl); +}; + +class SynapticsLibraryStubImpl : public SynapticsLibrary { + public: + SynapticsLibraryStubImpl() {} + virtual ~SynapticsLibraryStubImpl() {} + void SetBoolParameter(SynapticsParameter param, bool value) {} + void SetRangeParameter(SynapticsParameter param, int value) {} + + private: + DISALLOW_COPY_AND_ASSIGN(SynapticsLibraryStubImpl); +}; + +// static +SynapticsLibrary* SynapticsLibrary::GetImpl(bool stub) { + if (stub) + return new SynapticsLibraryStubImpl(); + else + return new SynapticsLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/synaptics_library.h b/chrome/browser/chromeos/cros/synaptics_library.h index fc5a80e..17a302f 100644 --- a/chrome/browser/chromeos/cros/synaptics_library.h +++ b/chrome/browser/chromeos/cros/synaptics_library.h @@ -25,32 +25,12 @@ class SynapticsLibrary { // Sets a range parameter. The actual call will be run on the FILE thread. // Value should be between 1 and 10 inclusive. virtual void SetRangeParameter(SynapticsParameter param, int value) = 0; -}; - - -// This class handles the interaction with the ChromeOS synaptics library APIs. -// Users can get an instance of this library class like this: -// SynapticsLibrary::Get() -// For a list of SynapticsPrameters, see chromeos_synaptics.h -// in third_party/cros or /usr/include/cros -class SynapticsLibraryImpl : public SynapticsLibrary { - public: - SynapticsLibraryImpl() {} - virtual ~SynapticsLibraryImpl() {} - - // SynapticsLibrary overrides. - virtual void SetBoolParameter(SynapticsParameter param, bool value); - virtual void SetRangeParameter(SynapticsParameter param, int value); - private: - - // This helper methods calls into the libcros library to set the parameter. - // This call is run on the FILE thread. - void SetParameter(SynapticsParameter param, int value); - - DISALLOW_COPY_AND_ASSIGN(SynapticsLibraryImpl); + // Get library implementation. + static SynapticsLibrary* GetImpl(bool stub); }; + } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_CROS_SYNAPTICS_LIBRARY_H_ diff --git a/chrome/browser/chromeos/cros/syslogs_library.cc b/chrome/browser/chromeos/cros/syslogs_library.cc index 365e9fe..7c5f4fa 100644 --- a/chrome/browser/chromeos/cros/syslogs_library.cc +++ b/chrome/browser/chromeos/cros/syslogs_library.cc @@ -10,11 +10,38 @@ namespace chromeos { -LogDictionaryType* SyslogsLibraryImpl::GetSyslogs(FilePath* tmpfilename) { - if (CrosLibrary::Get()->EnsureLoaded()) { - return chromeos::GetSystemLogs(tmpfilename); +class SyslogsLibraryImpl : public SyslogsLibrary { + public: + SyslogsLibraryImpl() {} + virtual ~SyslogsLibraryImpl() {} + + LogDictionaryType* GetSyslogs(FilePath* tmpfilename) { + if (CrosLibrary::Get()->EnsureLoaded()) { + return chromeos::GetSystemLogs(tmpfilename); + } + return NULL; + } +}; + +class SyslogsLibraryStubImpl : public SyslogsLibrary { + public: + SyslogsLibraryStubImpl() {} + virtual ~SyslogsLibraryStubImpl() {} + + LogDictionaryType* GetSyslogs(FilePath* tmpfilename) { + return &log_dictionary_; } - return NULL; + + private: + LogDictionaryType log_dictionary_; +}; + +// static +SyslogsLibrary* SyslogsLibrary::GetImpl(bool stub) { + if (stub) + return new SyslogsLibraryStubImpl(); + else + return new SyslogsLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/syslogs_library.h b/chrome/browser/chromeos/cros/syslogs_library.h index f043b59..a01dbec 100644 --- a/chrome/browser/chromeos/cros/syslogs_library.h +++ b/chrome/browser/chromeos/cros/syslogs_library.h @@ -19,19 +19,9 @@ class SyslogsLibrary { // System logs gathered for userfeedback virtual LogDictionaryType* GetSyslogs(FilePath* tmpfilename) = 0; -}; - - -// This class handles the interaction with the ChromeOS syslogs APIs. -class SyslogsLibraryImpl : public SyslogsLibrary { - public: - SyslogsLibraryImpl() {} - virtual ~SyslogsLibraryImpl() {} - - virtual LogDictionaryType* GetSyslogs(FilePath* tmpfilename); - private: - DISALLOW_COPY_AND_ASSIGN(SyslogsLibraryImpl); + // Get library implementation. + static SyslogsLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/system_library.cc b/chrome/browser/chromeos/cros/system_library.cc index 7f528d1..e09172b 100644 --- a/chrome/browser/chromeos/cros/system_library.cc +++ b/chrome/browser/chromeos/cros/system_library.cc @@ -9,47 +9,86 @@ namespace chromeos { -SystemLibraryImpl::SystemLibraryImpl() { - std::string id = "US/Pacific"; - if (CrosLibrary::Get()->EnsureLoaded()) { - std::string timezone_id = chromeos::GetTimezoneID(); - if (timezone_id.empty()) { - LOG(ERROR) << "Got an empty string for timezone, default to " << id; - } else { - id = timezone_id; +class SystemLibraryImpl : public SystemLibrary { + public: + SystemLibraryImpl() { + std::string id = "US/Pacific"; + if (CrosLibrary::Get()->EnsureLoaded()) { + std::string timezone_id = chromeos::GetTimezoneID(); + if (timezone_id.empty()) { + LOG(ERROR) << "Got an empty string for timezone, default to " << id; + } else { + id = timezone_id; + } } + icu::TimeZone* timezone = + icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(id)); + timezone_.reset(timezone); + icu::TimeZone::setDefault(*timezone); + LOG(INFO) << "Timezone is " << id; } - icu::TimeZone* timezone = - icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(id)); - timezone_.reset(timezone); - icu::TimeZone::setDefault(*timezone); - LOG(INFO) << "Timezone is " << id; -} -void SystemLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void SystemLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -const icu::TimeZone& SystemLibraryImpl::GetTimezone() { - return *timezone_.get(); -} + const icu::TimeZone& GetTimezone() { + return *timezone_.get(); + } + + void SetTimezone(const icu::TimeZone* timezone) { + timezone_.reset(timezone->clone()); + if (CrosLibrary::Get()->EnsureLoaded()) { + icu::UnicodeString unicode; + timezone->getID(unicode); + std::string id; + UTF16ToUTF8(unicode.getBuffer(), unicode.length(), &id); + LOG(INFO) << "Setting timezone to " << id; + chromeos::SetTimezoneID(id); + } + icu::TimeZone::setDefault(*timezone); + FOR_EACH_OBSERVER(Observer, observers_, TimezoneChanged(*timezone)); + } + + private: + scoped_ptr<icu::TimeZone> timezone_; + ObserverList<Observer> observers_; + + DISALLOW_COPY_AND_ASSIGN(SystemLibraryImpl); +}; -void SystemLibraryImpl::SetTimezone(const icu::TimeZone* timezone) { - timezone_.reset(timezone->clone()); - if (CrosLibrary::Get()->EnsureLoaded()) { - icu::UnicodeString unicode; - timezone->getID(unicode); - std::string id; - UTF16ToUTF8(unicode.getBuffer(), unicode.length(), &id); - LOG(INFO) << "Setting timezone to " << id; - chromeos::SetTimezoneID(id); +class SystemLibraryStubImpl : public SystemLibrary { + public: + SystemLibraryStubImpl() { + std::string id = "US/Pacific"; + icu::TimeZone* timezone = + icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(id)); + timezone_.reset(timezone); } - icu::TimeZone::setDefault(*timezone); - FOR_EACH_OBSERVER(Observer, observers_, TimezoneChanged(*timezone)); + ~SystemLibraryStubImpl() {} + + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} + const icu::TimeZone& GetTimezone() { + return *timezone_.get(); + } + void SetTimezone(const icu::TimeZone* timezone) {} + + private: + scoped_ptr<icu::TimeZone> timezone_; + DISALLOW_COPY_AND_ASSIGN(SystemLibraryStubImpl); +}; + +// static +SystemLibrary* SystemLibrary::GetImpl(bool stub) { + if (stub) + return new SystemLibraryStubImpl(); + else + return new SystemLibraryImpl(); } } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/system_library.h b/chrome/browser/chromeos/cros/system_library.h index c84905f..b81cc4c 100644 --- a/chrome/browser/chromeos/cros/system_library.h +++ b/chrome/browser/chromeos/cros/system_library.h @@ -33,26 +33,9 @@ class SystemLibrary { // Sets the current timezone. |timezone| must be non-null. virtual void SetTimezone(const icu::TimeZone* timezone) = 0; -}; - -// This class handles the interaction with the ChromeOS syslogs APIs. -class SystemLibraryImpl : public SystemLibrary { - public: - SystemLibraryImpl(); - virtual ~SystemLibraryImpl() {} - - // NetworkLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - - virtual const icu::TimeZone& GetTimezone(); - virtual void SetTimezone(const icu::TimeZone*); - - private: - scoped_ptr<icu::TimeZone> timezone_; - ObserverList<Observer> observers_; - DISALLOW_COPY_AND_ASSIGN(SystemLibraryImpl); + // Get library implementation. + static SystemLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/chromeos/cros/update_library.cc b/chrome/browser/chromeos/cros/update_library.cc index 320ab45..26a11ef 100644 --- a/chrome/browser/chromeos/cros/update_library.cc +++ b/chrome/browser/chromeos/cros/update_library.cc @@ -9,74 +9,114 @@ #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/cros/cros_library.h" -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); - namespace chromeos { -UpdateLibraryImpl::UpdateLibraryImpl() +class UpdateLibraryImpl : public UpdateLibrary { + public: + UpdateLibraryImpl() : status_connection_(NULL) { - if (CrosLibrary::Get()->EnsureLoaded()) { - Init(); + if (CrosLibrary::Get()->EnsureLoaded()) { + Init(); + } } -} -UpdateLibraryImpl::~UpdateLibraryImpl() { - if (status_connection_) { - DisconnectUpdateProgress(status_connection_); + ~UpdateLibraryImpl() { + if (status_connection_) { + DisconnectUpdateProgress(status_connection_); + } } -} -void UpdateLibraryImpl::AddObserver(Observer* observer) { - observers_.AddObserver(observer); -} + void AddObserver(Observer* observer) { + observers_.AddObserver(observer); + } -void UpdateLibraryImpl::RemoveObserver(Observer* observer) { - observers_.RemoveObserver(observer); -} + void RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); + } -bool UpdateLibraryImpl::CheckForUpdate() { - if (!CrosLibrary::Get()->EnsureLoaded()) - return false; + bool CheckForUpdate() { + if (!CrosLibrary::Get()->EnsureLoaded()) + return false; - return InitiateUpdateCheck(); -} + return InitiateUpdateCheck(); + } -bool UpdateLibraryImpl::RebootAfterUpdate() { - if (!CrosLibrary::Get()->EnsureLoaded()) - return false; + bool RebootAfterUpdate() { + if (!CrosLibrary::Get()->EnsureLoaded()) + return false; - return RebootIfUpdated(); -} + return RebootIfUpdated(); + } -const UpdateLibrary::Status& UpdateLibraryImpl::status() const { - return status_; -} + const UpdateLibrary::Status& status() const { + return status_; + } -// static -void UpdateLibraryImpl::ChangedHandler(void* object, - const UpdateProgress& status) { - UpdateLibraryImpl* updater = static_cast<UpdateLibraryImpl*>(object); - updater->UpdateStatus(Status(status)); -} + private: + static void ChangedHandler(void* object, + const UpdateProgress& status) { + UpdateLibraryImpl* updater = static_cast<UpdateLibraryImpl*>(object); + updater->UpdateStatus(Status(status)); + } -void UpdateLibraryImpl::Init() { - status_connection_ = MonitorUpdateStatus(&ChangedHandler, this); -} + void Init() { + status_connection_ = MonitorUpdateStatus(&ChangedHandler, this); + } -void UpdateLibraryImpl::UpdateStatus(const Status& status) { - // Make sure we run on UI thread. - if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { - ChromeThread::PostTask( - ChromeThread::UI, FROM_HERE, - NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); - return; + void UpdateStatus(const Status& status) { + // Make sure we run on UI thread. + if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) { + ChromeThread::PostTask( + ChromeThread::UI, FROM_HERE, + NewRunnableMethod(this, &UpdateLibraryImpl::UpdateStatus, status)); + return; + } + + status_ = status; + FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); } - status_ = status; - FOR_EACH_OBSERVER(Observer, observers_, UpdateStatusChanged(this)); + ObserverList<Observer> observers_; + + // A reference to the update api, to allow callbacks when the update + // status changes. + UpdateStatusConnection status_connection_; + + // The latest power status. + Status status_; + + DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); +}; + +class UpdateLibraryStubImpl : public UpdateLibrary { + public: + UpdateLibraryStubImpl() {} + ~UpdateLibraryStubImpl() {} + void AddObserver(Observer* observer) {} + void RemoveObserver(Observer* observer) {} + bool CheckForUpdate() { return false; } + bool RebootAfterUpdate() { return false; } + const UpdateLibrary::Status& status() const { + return status_; + } + + private: + Status status_; + + DISALLOW_COPY_AND_ASSIGN(UpdateLibraryStubImpl); +}; + +// static +UpdateLibrary* UpdateLibrary::GetImpl(bool stub) { + if (stub) + return new UpdateLibraryStubImpl(); + else + return new UpdateLibraryImpl(); } } // namespace chromeos +// Allows InvokeLater without adding refcounting. This class is a Singleton and +// won't be deleted until it's last InvokeLater is run. +DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::UpdateLibraryImpl); + diff --git a/chrome/browser/chromeos/cros/update_library.h b/chrome/browser/chromeos/cros/update_library.h index 223426e..8fed212 100644 --- a/chrome/browser/chromeos/cros/update_library.h +++ b/chrome/browser/chromeos/cros/update_library.h @@ -56,6 +56,8 @@ class UpdateLibrary { virtual void UpdateStatusChanged(UpdateLibrary* library) = 0; }; +// static UpdateLibrary* GetStubImplementation(); + virtual ~UpdateLibrary() {} virtual void AddObserver(Observer* observer) = 0; virtual void RemoveObserver(Observer* observer) = 0; @@ -67,44 +69,9 @@ class UpdateLibrary { virtual bool RebootAfterUpdate() = 0; virtual const Status& status() const = 0; -}; - -class UpdateLibraryImpl : public UpdateLibrary { - public: - UpdateLibraryImpl(); - virtual ~UpdateLibraryImpl(); - - // UpdateLibrary overrides. - virtual void AddObserver(Observer* observer); - virtual void RemoveObserver(Observer* observer); - - virtual bool CheckForUpdate(); - virtual bool RebootAfterUpdate(); - virtual const Status& status() const; - - private: - - // This method is called when there's a change in status. - // This method is called on a background thread. - static void ChangedHandler(void* object, const UpdateProgress& status); - - // This methods starts the monitoring of power changes. - void Init(); - - // Called by the handler to update the power status. - // This will notify all the Observers. - void UpdateStatus(const Status& status); - - ObserverList<Observer> observers_; - - // A reference to the update api, to allow callbacks when the update - // status changes. - UpdateStatusConnection status_connection_; - - // The latest power status. - Status status_; - DISALLOW_COPY_AND_ASSIGN(UpdateLibraryImpl); + // Get library implementation. + static UpdateLibrary* GetImpl(bool stub); }; } // namespace chromeos diff --git a/chrome/browser/geolocation/wifi_data_provider_chromeos.cc b/chrome/browser/geolocation/wifi_data_provider_chromeos.cc index bb1d936..a13d2f7 100644 --- a/chrome/browser/geolocation/wifi_data_provider_chromeos.cc +++ b/chrome/browser/geolocation/wifi_data_provider_chromeos.cc @@ -7,6 +7,7 @@ #include "chrome/browser/geolocation/wifi_data_provider_chromeos.h" #include "base/utf_string_conversions.h" +#include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" namespace { @@ -85,7 +86,7 @@ WifiDataProviderCommon::WlanApiInterface* WifiDataProviderCommon::WlanApiInterface* WifiDataProviderChromeOs::NewWlanApi() { if (network_library_ == NULL) { - network_library_.reset(new chromeos::NetworkLibraryImpl()); + network_library_.reset(chromeos::CrosLibrary::Get()->GetNetworkLibrary()); // TODO(joth): Check net_lib loaded ok, if not return NULL. } return NewWlanApi(network_library_.get()); diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index cdd7878..31ee236 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc @@ -1026,7 +1026,6 @@ const char kLoginManager[] = "login-manager"; const char kLoginScreen[] = "login-screen"; // Allows control over the initial login screen size. Pass width,height. const char kLoginScreenSize[] = "login-screen-size"; - // Attempts to load libcros and validate it, then exits. A nonzero return code // means the library could not be loaded correctly. const char kTestLoadLibcros[] = "test-load-libcros"; @@ -1036,6 +1035,8 @@ const char kLoginProfile[] = "login-profile"; // Specifies the user which is already logged in. const char kLoginUser[] = "login-user"; +// Specifies a password to be used to login (along with login-user). +const char kLoginPassword[] = "login-password"; // Use the frame layout used in chromeos. const char kChromeosFrame[] = "chromeos-frame"; @@ -1047,6 +1048,9 @@ const char kChromeosLogToFile[] = "logtofile"; // Should completely disable extensions, sync and bookmarks. const char kBWSI[] = "bwsi"; +// Indicates that stub implementations of the libcros library should be used. +// This is typically used to test the chromeos build of chrome on the desktop. +const char kStubCros[] = "stub-cros"; #endif #if defined(OS_LINUX) diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index 1069d00..7e486b2 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h @@ -299,9 +299,11 @@ extern const char kLoginScreenSize[]; extern const char kTestLoadLibcros[]; extern const char kLoginProfile[]; extern const char kLoginUser[]; +extern const char kLoginPassword[]; extern const char kChromeosFrame[]; extern const char kChromeosLogToFile[]; extern const char kBWSI[]; +extern const char kStubCros[]; #endif #if defined(OS_LINUX) |