diff --git a/WATCHLISTS b/WATCHLISTS index 110511269ba22..5351d4a26e688 100644 --- a/WATCHLISTS +++ b/WATCHLISTS @@ -907,13 +907,6 @@ 'filepath': 'chrome/browser/resources/(md_)?history|'\ 'chrome/browser/ui/webui/.*history', }, - 'hotword': { - 'filepath': 'chrome/browser/extensions/api/hotword_private/'\ - '|chrome/browser/resources/hotword_helper/'\ - '|chrome/browser/resources/hotword/'\ - '|chrome/browser/search/hotword*'\ - '|chrome/test/data/extensions/api_test/hotword_private/', - }, 'i18n': { 'filepath': 'base/i18n/|base/string|l10n|icu|'\ 'locale_settings|encoding', @@ -2049,7 +2042,6 @@ 'gpu_passthrough_cmd_decoder': ['cwallez+watch@chromium.org', 'geofflang+watch@chromium.org'], 'history_ui': ['pam+watch@chromium.org'], - 'hotword': ['rlp+watch@chromium.org'], 'i18n': ['jshin+watch@chromium.org'], 'importer': ['tfarina@chromium.org'], 'incident_reporting': ['grt+watch@chromium.org'], diff --git a/ash/app_list/model/search_box_model.cc b/ash/app_list/model/search_box_model.cc index d94c542dbae23..e91012bf690ab 100644 --- a/ash/app_list/model/search_box_model.cc +++ b/ash/app_list/model/search_box_model.cc @@ -12,16 +12,10 @@ namespace app_list { SearchBoxModel::SpeechButtonProperty::SpeechButtonProperty( - const gfx::ImageSkia& on_icon, - const base::string16& on_tooltip, - const gfx::ImageSkia& off_icon, - const base::string16& off_tooltip, + const gfx::ImageSkia& icon, + const base::string16& tooltip, const base::string16& accessible_name) - : on_icon(on_icon), - on_tooltip(on_tooltip), - off_icon(off_icon), - off_tooltip(off_tooltip), - accessible_name(accessible_name) {} + : icon(icon), tooltip(tooltip), accessible_name(accessible_name) {} SearchBoxModel::SpeechButtonProperty::~SpeechButtonProperty() = default; diff --git a/ash/app_list/model/search_box_model.h b/ash/app_list/model/search_box_model.h index 450698a57f9d1..f20f74be024b2 100644 --- a/ash/app_list/model/search_box_model.h +++ b/ash/app_list/model/search_box_model.h @@ -5,6 +5,8 @@ #ifndef ASH_APP_LIST_MODEL_SEARCH_BOX_MODEL_H_ #define ASH_APP_LIST_MODEL_SEARCH_BOX_MODEL_H_ +#include + #include "ash/app_list/model/app_list_model_export.h" #include "base/macros.h" #include "base/observer_list.h" @@ -25,20 +27,13 @@ class APP_LIST_MODEL_EXPORT SearchBoxModel { public: // The properties of the speech button. struct APP_LIST_MODEL_EXPORT SpeechButtonProperty { - SpeechButtonProperty(const gfx::ImageSkia& on_icon, - const base::string16& on_tooltip, - const gfx::ImageSkia& off_icon, - const base::string16& off_tooltip, + SpeechButtonProperty(const gfx::ImageSkia& icon, + const base::string16& tooltip, const base::string16& accessible_name); ~SpeechButtonProperty(); - // The icon/tooltip when the hotword is on. - gfx::ImageSkia on_icon; - base::string16 on_tooltip; - - // The icon/tooltip when the hotword is off. - gfx::ImageSkia off_icon; - base::string16 off_tooltip; + gfx::ImageSkia icon; + base::string16 tooltip; // The accessibility name of the button. base::string16 accessible_name; diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 3851d61ff1cc5..662909f65bd5f 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd @@ -4799,15 +4799,6 @@ Keep your key file in a safe place. You will need it to create new versions of y Set which search engine is used when searching from the <a target="_blank" href="$1">omnibox</a></a>. - - This feature is temporarily unavailable. <a target="_blank" href="$1">Help</a></a> - - - Native Client plugin needs to be enabled to use this feature. - - - Microphone is currently unavailable. <a target="_blank" href="chrome://settings/content#media-stream-settings">Manage microphone</a></a> - @@ -5079,16 +5070,6 @@ Keep your key file in a safe place. You will need it to create new versions of y This page uses a Native Client app that doesn't work on your computer. - - - - Loading... - - - About Voice Search - - - @@ -9882,9 +9863,6 @@ For more information, visit our <a target="_blank" href Click to start voice search - - Click, or say "Ok Google" to start voice search - Search your device, apps, and web. Use the arrow keys to navigate your apps. @@ -9897,9 +9875,6 @@ For more information, visit our <a target="_blank" href Search your device, apps, web... - - Search, or say "Ok Google" - New tab @@ -10536,115 +10511,6 @@ For more information, visit our <a target="_blank" href Select - - - $1Chromium browser - - - Close - - - CANCEL - - - Voice search at any time - - - Say "Ok Google" when your screen is on and unlocked - - - To make this happen, you'll need to enable Voice & Audio Activity and train your $1Chromebook in the following steps. - - - To make this happen, you'll need to train your $1Chromebook in the following step. - - - Get Started - - - Enable Voice & Audio Activity - - - When you use audio activation commands, such as "Ok Google" or touching a microphone icon, your private Voice & Audio Activity stores some voice and other audio to your account. A recording of the following speech/audio, plus a few seconds before, will be stored. - - - This helps Google recognize your voice and improve speech and audio recognition in order to give you results faster and with fewer hassles. <a target="_blank" href="https://support.google.com/websearch?p=chromebook_audiohistory">Learn more</a></a> - - - You can change this setting or <a target="_blank" href="https://history.google.com/history/audio">manage your private data</a></a> whenever you like. Please remember that when Voice & Audio Activity is on, this data may be saved from any of your signed-in devices. - - - Enable - - - Enabling Voice & Audio Activity... - - - Something went wrong. Please try again. - - - Let's train your $1Chromebook - - - To help your $1Chromebook respond to you and for reliable and easy access to voice search, you need to teach Google the sound of your voice. - - - Just say "Ok Google" three times - - - Say "Ok Google" - - - Say "Ok Google" again - - - Say "Ok Google" one last time - - - Complete - - - Training timed out - - - RETRY - - - You're all set! - - - Your $1Chromebook can now: - - - Recognize your voice when you say "Ok Google" - - - Respond to "Ok Google" when the screen is on and unlocked - - - You can change this at any time in <a target="_blank" href="#" id="settings-link">Chrome Settings</a></a>. - - - Search queries will be tied to your Google Account. You can view and delete them in your <a target="_blank" href="https://www.google.com/settings/accounthistory">Account History</a></a>. - - - OK - - - Processing... - - - - - Voice search at any time - - - Enable "Ok Google" to voice search when your screen is on and unlocked - - - Enable "Ok Google" - - Device Log diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 11eca0f8ae6e0..524559d88ce16 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp @@ -2243,36 +2243,6 @@ Manage search engines - - Enable "Ok Google" to start a voice search - - - - "Ok Google" voice search has been removed from Chrome OS - - - - Say "Ok Google" when the screen is on and unlocked - - - - Say "Ok Google" in a new tab, google.com, and the App Launcher - - - - - Say "Ok Google" in a new tab and google.com - - - - Voice and Audio Activity for $1joe@gmail.com. - - - Enabled (required to use "Ok Google") - - - Retrain - Google Assistant diff --git a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png b/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png deleted file mode 100644 index 9f7db87d8bd18..0000000000000 Binary files a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_off.png and /dev/null differ diff --git a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png b/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png deleted file mode 100644 index ad216daedc7fc..0000000000000 Binary files a/chrome/app/theme/default_100_percent/common/app_list_mic_hotword_on.png and /dev/null differ diff --git a/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png b/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png deleted file mode 100644 index 95c161bc27845..0000000000000 Binary files a/chrome/app/theme/default_100_percent/common/notification_hotword_icon.png and /dev/null differ diff --git a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png b/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png deleted file mode 100644 index 9d82452306801..0000000000000 Binary files a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_off.png and /dev/null differ diff --git a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png b/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png deleted file mode 100644 index 26510654dca57..0000000000000 Binary files a/chrome/app/theme/default_200_percent/common/app_list_mic_hotword_on.png and /dev/null differ diff --git a/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png b/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png deleted file mode 100644 index 914ce662b5581..0000000000000 Binary files a/chrome/app/theme/default_200_percent/common/notification_hotword_icon.png and /dev/null differ diff --git a/chrome/app/theme/theme_resources.grd b/chrome/app/theme/theme_resources.grd index 0a3d77ceddc92..f7dd5feae4317 100644 --- a/chrome/app/theme/theme_resources.grd +++ b/chrome/app/theme/theme_resources.grd @@ -48,8 +48,6 @@ - - @@ -200,7 +198,6 @@ - diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 4fdb25fd00ec4..4cfa1fcb6d4a0 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn @@ -3366,13 +3366,6 @@ split_static_library("browser") { "renderer_context_menu/context_menu_content_type_platform_app.h", "renderer_host/chrome_extension_message_filter.cc", "renderer_host/chrome_extension_message_filter.h", - "search/hotword_audio_history_handler.cc", - "search/hotword_audio_history_handler.h", - "search/hotword_client.h", - "search/hotword_service.cc", - "search/hotword_service.h", - "search/hotword_service_factory.cc", - "search/hotword_service_factory.h", "signin/chrome_proximity_auth_client.cc", "signin/chrome_proximity_auth_client.h", "signin/easy_unlock_app_manager.cc", @@ -3542,10 +3535,6 @@ split_static_library("browser") { ] } - if (enable_hotwording) { - defines += [ "ENABLE_HOTWORDING" ] - } - if (enable_mdns) { sources += [ "local_discovery/service_discovery_client_impl.cc", diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9472d68e3eacd..d9e9be83389f6 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc @@ -1948,10 +1948,6 @@ const FeatureEntry kFeatureEntries[] = { flag_descriptions::kUserConsentForExtensionScriptsDescription, kOsAll, SINGLE_VALUE_TYPE(extensions::switches::kEnableScriptsRequireAction)}, #endif // ENABLE_EXTENSIONS - {"enable-hotword-hardware", - flag_descriptions::kExperimentalHotwordHardwareName, - flag_descriptions::kExperimentalHotwordHardwareDescription, kOsCrOS, - SINGLE_VALUE_TYPE(switches::kEnableExperimentalHotwordHardware)}, #if BUILDFLAG(ENABLE_EXTENSIONS) {"enable-embedded-extension-options", flag_descriptions::kEmbeddedExtensionOptionsName, diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 3dcea99ea2653..01e3df3a3920b 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd @@ -199,10 +199,6 @@ - - - - @@ -375,8 +371,6 @@ - - diff --git a/chrome/browser/extensions/BUILD.gn b/chrome/browser/extensions/BUILD.gn index 66b71f75b0c84..32dad4f42e7f0 100644 --- a/chrome/browser/extensions/BUILD.gn +++ b/chrome/browser/extensions/BUILD.gn @@ -201,8 +201,6 @@ static_library("extensions") { "api/gcm/gcm_api.h", "api/history/history_api.cc", "api/history/history_api.h", - "api/hotword_private/hotword_private_api.cc", - "api/hotword_private/hotword_private_api.h", "api/i18n/i18n_api.cc", "api/i18n/i18n_api.h", "api/identity/extension_token_key.cc", @@ -1116,10 +1114,6 @@ static_library("extensions") { ] } - if (enable_hotwording) { - defines += [ "ENABLE_HOTWORDING" ] - } - if (enable_service_discovery) { sources += [ "api/mdns/mdns_api.cc", diff --git a/chrome/browser/extensions/api/hotword_private/OWNERS b/chrome/browser/extensions/api/hotword_private/OWNERS deleted file mode 100644 index 2ae98b3a1f11e..0000000000000 --- a/chrome/browser/extensions/api/hotword_private/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -kcarattini@chromium.org -mgiuca@chromium.org diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc b/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc deleted file mode 100644 index 6976c1b83bff3..0000000000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_api.cc +++ /dev/null @@ -1,540 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" - -#include -#include -#include - -#include "base/lazy_instance.h" -#include "base/memory/ptr_util.h" -#include "base/strings/utf_string_conversions.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_client.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/app_list/app_list_service.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/pref_names.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/speech_recognition_session_preamble.h" -#include "extensions/browser/event_router.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/webui/web_ui_util.h" - -#if defined(OS_CHROMEOS) -#include "ui/chromeos/devicetype_utils.h" -#endif - -namespace extensions { - -namespace hotword_private_constants { -const char kHotwordServiceUnavailable[] = "Hotword Service is unavailable."; -const char kHotwordEventServiceUnavailable[] = - "Hotword Private Event Service is unavailable."; -} // hotword_private_constants - -namespace OnEnabledChanged = - api::hotword_private::OnEnabledChanged; - -static base::LazyInstance< - BrowserContextKeyedAPIFactory>::DestructorAtExit - g_hotword_private_api_factory = LAZY_INSTANCE_INITIALIZER; - -HotwordPrivateEventService::HotwordPrivateEventService( - content::BrowserContext* context) - : profile_(Profile::FromBrowserContext(context)) { - pref_change_registrar_.Init(profile_->GetPrefs()); - pref_change_registrar_.Add( - prefs::kHotwordSearchEnabled, - base::Bind(&HotwordPrivateEventService::OnEnabledChanged, - base::Unretained(this))); - pref_change_registrar_.Add( - prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&HotwordPrivateEventService::OnEnabledChanged, - base::Unretained(this))); -} - -HotwordPrivateEventService::~HotwordPrivateEventService() { -} - -void HotwordPrivateEventService::Shutdown() { -} - -// static -BrowserContextKeyedAPIFactory* -HotwordPrivateEventService::GetFactoryInstance() { - return g_hotword_private_api_factory.Pointer(); -} - -// static -const char* HotwordPrivateEventService::service_name() { - return "HotwordPrivateEventService"; -} - -void HotwordPrivateEventService::OnEnabledChanged( - const std::string& pref_name) { - DCHECK(pref_name == std::string(prefs::kHotwordSearchEnabled) || - pref_name == std::string(prefs::kHotwordAlwaysOnSearchEnabled) || - pref_name == std::string( - hotword_internal::kHotwordTrainingEnabled)); - SignalEvent(events::HOTWORD_PRIVATE_ON_ENABLED_CHANGED, - OnEnabledChanged::kEventName); -} - -void HotwordPrivateEventService::OnHotwordSessionRequested() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_SESSION_REQUESTED, - api::hotword_private::OnHotwordSessionRequested::kEventName); -} - -void HotwordPrivateEventService::OnHotwordSessionStopped() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_SESSION_STOPPED, - api::hotword_private::OnHotwordSessionStopped::kEventName); -} - -void HotwordPrivateEventService::OnFinalizeSpeakerModel() { - SignalEvent(events::HOTWORD_PRIVATE_ON_FINALIZE_SPEAKER_MODEL, - api::hotword_private::OnFinalizeSpeakerModel::kEventName); -} - -void HotwordPrivateEventService::OnSpeakerModelSaved() { - SignalEvent(events::HOTWORD_PRIVATE_ON_SPEAKER_MODEL_SAVED, - api::hotword_private::OnSpeakerModelSaved::kEventName); -} - -void HotwordPrivateEventService::OnHotwordTriggered() { - SignalEvent(events::HOTWORD_PRIVATE_ON_HOTWORD_TRIGGERED, - api::hotword_private::OnHotwordTriggered::kEventName); -} - -void HotwordPrivateEventService::OnDeleteSpeakerModel() { - SignalEvent(events::HOTWORD_PRIVATE_ON_DELETE_SPEAKER_MODEL, - api::hotword_private::OnDeleteSpeakerModel::kEventName); -} - -void HotwordPrivateEventService::OnSpeakerModelExists() { - SignalEvent(events::HOTWORD_PRIVATE_ON_SPEAKER_MODEL_EXISTS, - api::hotword_private::OnSpeakerModelExists::kEventName); -} - -void HotwordPrivateEventService::OnMicrophoneStateChanged(bool enabled) { - SignalEvent(events::HOTWORD_PRIVATE_ON_MICROPHONE_STATE_CHANGED, - api::hotword_private::OnMicrophoneStateChanged::kEventName, - api::hotword_private::OnMicrophoneStateChanged::Create(enabled)); -} - -void HotwordPrivateEventService::SignalEvent( - events::HistogramValue histogram_value, - const std::string& event_name) { - SignalEvent(histogram_value, event_name, base::MakeUnique()); -} - -void HotwordPrivateEventService::SignalEvent( - events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr args) { - EventRouter* router = EventRouter::Get(profile_); - if (!router || !router->HasEventListener(event_name)) - return; - - std::unique_ptr event( - new Event(histogram_value, event_name, std::move(args))); - router->BroadcastEvent(std::move(event)); -} - -ExtensionFunction::ResponseAction HotwordPrivateSetEnabledFunction::Run() { - std::unique_ptr params( - api::hotword_private::SetEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordSearchEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetAudioLoggingEnabledFunction::Run() { - std::unique_ptr params( - api::hotword_private::SetAudioLoggingEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - // TODO(kcarattini): Sync the chrome pref with the account-level - // Audio History setting. - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction::Run() { - std::unique_ptr - params( - api::hotword_private::SetHotwordAlwaysOnSearchEnabled::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - PrefService* prefs = - Profile::FromBrowserContext(browser_context())->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, params->state); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateGetStatusFunction::Run() { - std::unique_ptr params( - api::hotword_private::GetStatus::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - api::hotword_private::StatusDetails result; - - Profile* profile = Profile::FromBrowserContext(browser_context()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile); - if (!hotword_service) { - result.available = false; - result.always_on_available = false; - result.enabled = false; - result.audio_logging_enabled = false; - result.always_on_enabled = false; - result.user_is_active = false; - result.hotword_hardware_available = false; - } else { - result.available = false; - result.always_on_available = false; - if (params->get_optional_fields && *params->get_optional_fields) { - result.available = hotword_service->IsServiceAvailable(); - result.always_on_available = - HotwordServiceFactory::IsAlwaysOnAvailable(); - } - result.enabled = hotword_service->IsSometimesOnEnabled(); - result.audio_logging_enabled = hotword_service->IsOptedIntoAudioLogging(); - result.training_enabled = hotword_service->IsTraining(); - result.always_on_enabled = hotword_service->IsAlwaysOnEnabled(); - result.user_is_active = hotword_service->UserIsActive(); - result.hotword_hardware_available = - HotwordService::IsHotwordHardwareAvailable(); - } - - PrefService* prefs = profile->GetPrefs(); - result.enabled_set = prefs->HasPrefPath(prefs::kHotwordSearchEnabled); - - return RespondNow(OneArgument(result.ToValue())); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSetHotwordSessionStateFunction::Run() { - std::unique_ptr params( - api::hotword_private::SetHotwordSessionState::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (hotword_service && - hotword_service->client() && - !hotword_service->IsTraining()) - hotword_service->client()->OnHotwordStateChanged(params->started); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateNotifyHotwordRecognitionFunction::Run() { - std::unique_ptr - params(api::hotword_private::NotifyHotwordRecognition::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - scoped_refptr preamble; - if (params->log.get() && - !params->log->buffer.empty() && - params->log->channels == 1) { - // TODO(amistry): Convert multi-channel preamble log into mono. - preamble = new content::SpeechRecognitionSessionPreamble(); - preamble->sample_rate = params->log->sample_rate; - preamble->sample_depth = params->log->bytes_per_sample; - preamble->sample_data.swap(params->log->buffer); - } - - Profile* profile = Profile::FromBrowserContext(browser_context()); - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile); - if (hotword_service) { - if (hotword_service->IsTraining()) { - hotword_service->NotifyHotwordTriggered(); - } else if (hotword_service->client()) { - hotword_service->client()->OnHotwordRecognized(preamble); - } else if (hotword_service->IsAlwaysOnEnabled()) { - AppListService* app_list_service = AppListService::Get(); - CHECK(app_list_service); - app_list_service->ShowForVoiceSearch(profile, preamble); - } - } - - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateGetLaunchStateFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - api::hotword_private::LaunchState result; - result.launch_mode = - hotword_service->GetHotwordAudioVerificationLaunchMode(); - return RespondNow(OneArgument(result.ToValue())); -} - -ExtensionFunction::ResponseAction HotwordPrivateStartTrainingFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->StartTraining(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateFinalizeSpeakerModelFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->FinalizeSpeakerModel(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateNotifySpeakerModelSavedFunction::Run() { - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get( - Profile::FromBrowserContext(browser_context())); - if (!event_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordEventServiceUnavailable)); - } - - event_service->OnSpeakerModelSaved(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction HotwordPrivateStopTrainingFunction::Run() { - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) { - return RespondNow( - Error(hotword_private_constants::kHotwordServiceUnavailable)); - } - - hotword_service->StopTraining(); - return RespondNow(NoArguments()); -} - -ExtensionFunction::ResponseAction -HotwordPrivateGetLocalizedStringsFunction::Run() { -#if defined(OS_CHROMEOS) - base::string16 device_type = ui::GetChromeOSDeviceName(); -#else - base::string16 product_name = - l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME); - base::string16 device_type = - l10n_util::GetStringFUTF16(IDS_HOTWORD_BROWSER_NAME, product_name); -#endif - - std::unique_ptr localized_strings( - new base::DictionaryValue()); - - localized_strings->SetString( - "close", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_CLOSE)); - localized_strings->SetString( - "cancel", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_CANCEL)); - localized_strings->SetString( - "introTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_TITLE)); - localized_strings->SetString( - "introSubtitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_SUBTITLE)); - localized_strings->SetString( - "introDescription", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION, - device_type)); - localized_strings->SetString( - "introDescriptionAudioHistoryEnabled", - l10n_util::GetStringFUTF16( - IDS_HOTWORD_OPT_IN_INTRO_DESCRIPTION_AUDIO_HISTORY_ENABLED, - device_type)); - localized_strings->SetString( - "introStart", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_INTRO_START)); - localized_strings->SetString( - "audioHistoryTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_TITLE)); - localized_strings->SetString( - "audioHistoryDescription1", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_1)); - localized_strings->SetString( - "audioHistoryDescription2", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_2)); - localized_strings->SetString( - "audioHistoryDescription3", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_DESCRIPTION_3)); - localized_strings->SetString( - "audioHistoryAgree", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_AGREE)); - localized_strings->SetString( - "audioHistoryWait", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_AUDIO_HISTORY_WAIT)); - localized_strings->SetString( - "error", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_ERROR)); - localized_strings->SetString( - "trainingTitle", l10n_util::GetStringFUTF16( - IDS_HOTWORD_OPT_IN_TRAINING_TITLE, device_type)); - localized_strings->SetString( - "trainingDescription", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_TRAINING_DESCRIPTION, - device_type)); - localized_strings->SetString( - "trainingSpeak", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_SPEAK)); - localized_strings->SetString( - "trainingFirstPrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_FIRST_PROMPT)); - localized_strings->SetString( - "trainingMiddlePrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_MIDDLE_PROMPT)); - localized_strings->SetString( - "trainingLastPrompt", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_LAST_PROMPT)); - localized_strings->SetString( - "trainingRecorded", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_RECORDED)); - localized_strings->SetString( - "trainingTimeout", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_TIMEOUT)); - localized_strings->SetString( - "trainingRetry", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_TRAINING_RETRY)); - localized_strings->SetString( - "finishedTitle", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_TITLE)); - localized_strings->SetString( - "finishedListIntro", - l10n_util::GetStringFUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_INTRO, - device_type)); - localized_strings->SetString( - "finishedListItem1", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_1)); - localized_strings->SetString( - "finishedListItem2", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_LIST_ITEM_2)); - localized_strings->SetString( - "finishedSettings", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_SETTINGS)); - localized_strings->SetString( - "finishedAudioHistory", - l10n_util::GetStringUTF16( - IDS_HOTWORD_OPT_IN_FINISHED_AUDIO_HISTORY)); - localized_strings->SetString( - "finish", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISH)); - localized_strings->SetString( - "finishedWait", - l10n_util::GetStringUTF16(IDS_HOTWORD_OPT_IN_FINISHED_WAIT)); - - const std::string& app_locale = g_browser_process->GetApplicationLocale(); - webui::SetLoadTimeDataDefaults(app_locale, localized_strings.get()); - - return RespondNow(OneArgument(std::move(localized_strings))); -} - -bool HotwordPrivateSetAudioHistoryEnabledFunction::RunAsync() { - std::unique_ptr params( - api::hotword_private::SetAudioHistoryEnabled::Params::Create(*args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); - if (!hotword_service || !hotword_service->GetAudioHistoryHandler()) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; - } - - hotword_service->GetAudioHistoryHandler()->SetAudioHistoryEnabled( - params->enabled, - base::Bind( - &HotwordPrivateSetAudioHistoryEnabledFunction::SetResultAndSendResponse, - this)); - return true; -} - -void HotwordPrivateSetAudioHistoryEnabledFunction::SetResultAndSendResponse( - bool success, bool new_enabled_value) { - api::hotword_private::AudioHistoryState result; - result.success = success; - result.enabled = new_enabled_value; - SetResult(result.ToValue()); - SendResponse(true); -} - -bool HotwordPrivateGetAudioHistoryEnabledFunction::RunAsync() { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(GetProfile()); - if (!hotword_service || !hotword_service->GetAudioHistoryHandler()) { - error_ = hotword_private_constants::kHotwordServiceUnavailable; - return false; - } - - hotword_service->GetAudioHistoryHandler()->GetAudioHistoryEnabled(base::Bind( - &HotwordPrivateGetAudioHistoryEnabledFunction::SetResultAndSendResponse, - this)); - - return true; -} - -void HotwordPrivateGetAudioHistoryEnabledFunction::SetResultAndSendResponse( - bool success, bool new_enabled_value) { - api::hotword_private::AudioHistoryState result; - result.success = success; - result.enabled = new_enabled_value; - SetResult(result.ToValue()); - SendResponse(true); -} - -ExtensionFunction::ResponseAction -HotwordPrivateSpeakerModelExistsResultFunction::Run() { - std::unique_ptr - params(api::hotword_private::SpeakerModelExistsResult::Params::Create( - *args_)); - EXTENSION_FUNCTION_VALIDATE(params.get()); - - HotwordService* hotword_service = HotwordServiceFactory::GetForProfile( - Profile::FromBrowserContext(browser_context())); - if (!hotword_service) - return RespondNow(Error(kUnknownErrorDoNotUse)); - - hotword_service->SpeakerModelExistsComplete(params->exists); - return RespondNow(NoArguments()); -} - -} // namespace extensions diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_api.h b/chrome/browser/extensions/api/hotword_private/hotword_private_api.h deleted file mode 100644 index 1f3862460a8b1..0000000000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_api.h +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_ - -#include "base/values.h" -#include "chrome/browser/extensions/chrome_extension_function.h" -#include "chrome/common/extensions/api/hotword_private.h" -#include "components/prefs/pref_change_registrar.h" -#include "extensions/browser/browser_context_keyed_api_factory.h" -#include "extensions/browser/extension_event_histogram_value.h" - -class Profile; - -namespace extensions { - -// Listens for changes in disable/enabled state and forwards as an extension -// event. -class HotwordPrivateEventService : public BrowserContextKeyedAPI { - public: - explicit HotwordPrivateEventService(content::BrowserContext* context); - ~HotwordPrivateEventService() override; - - // BrowserContextKeyedAPI implementation. - void Shutdown() override; - static BrowserContextKeyedAPIFactory* - GetFactoryInstance(); - static const char* service_name(); - - void OnEnabledChanged(const std::string& pref_name); - - void OnHotwordSessionRequested(); - - void OnHotwordSessionStopped(); - - void OnHotwordTriggered(); - - void OnFinalizeSpeakerModel(); - - void OnSpeakerModelSaved(); - - void OnDeleteSpeakerModel(); - - void OnSpeakerModelExists(); - - void OnMicrophoneStateChanged(bool enabled); - - private: - friend class BrowserContextKeyedAPIFactory; - - void SignalEvent(events::HistogramValue histogram_value, - const std::string& event_name); - void SignalEvent(events::HistogramValue histogram_value, - const std::string& event_name, - std::unique_ptr args); - - Profile* profile_; - PrefChangeRegistrar pref_change_registrar_; -}; - -class HotwordPrivateSetEnabledFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setEnabled", - HOTWORDPRIVATE_SETENABLED) - - protected: - ~HotwordPrivateSetEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetAudioLoggingEnabledFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setAudioLoggingEnabled", - HOTWORDPRIVATE_SETAUDIOLOGGINGENABLED) - - protected: - ~HotwordPrivateSetAudioLoggingEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordAlwaysOnSearchEnabled", - HOTWORDPRIVATE_SETHOTWORDALWAYSONSEARCHENABLED) - - protected: - ~HotwordPrivateSetHotwordAlwaysOnSearchEnabledFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetStatusFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getStatus", - HOTWORDPRIVATE_GETSTATUS) - - protected: - ~HotwordPrivateGetStatusFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetHotwordSessionStateFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setHotwordSessionState", - HOTWORDPRIVATE_SETHOTWORDSESSIONSTATE); - - protected: - ~HotwordPrivateSetHotwordSessionStateFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateNotifyHotwordRecognitionFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifyHotwordRecognition", - HOTWORDPRIVATE_NOTIFYHOTWORDRECOGNITION); - - protected: - ~HotwordPrivateNotifyHotwordRecognitionFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetLaunchStateFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLaunchState", - HOTWORDPRIVATE_GETLAUNCHSTATE) - - protected: - ~HotwordPrivateGetLaunchStateFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateStartTrainingFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.startTraining", - HOTWORDPRIVATE_STARTTRAINING) - - protected: - ~HotwordPrivateStartTrainingFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateFinalizeSpeakerModelFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.finalizeSpeakerModel", - HOTWORDPRIVATE_FINALIZESPEAKERMODEL) - - protected: - ~HotwordPrivateFinalizeSpeakerModelFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateNotifySpeakerModelSavedFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.notifySpeakerModelSaved", - HOTWORDPRIVATE_NOTIFYSPEAKERMODELSAVED) - - protected: - ~HotwordPrivateNotifySpeakerModelSavedFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateStopTrainingFunction : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.stopTraining", - HOTWORDPRIVATE_STOPTRAINING) - - protected: - ~HotwordPrivateStopTrainingFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateGetLocalizedStringsFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getLocalizedStrings", - HOTWORDPRIVATE_GETLOCALIZEDSTRINGS) - - protected: - ~HotwordPrivateGetLocalizedStringsFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -class HotwordPrivateSetAudioHistoryEnabledFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.setAudioHistoryEnabled", - HOTWORDPRIVATE_SETAUDIOHISTORYENABLED) - - protected: - ~HotwordPrivateSetAudioHistoryEnabledFunction() override {} - - // ExtensionFunction: - bool RunAsync() override; - - void SetResultAndSendResponse(bool success, bool new_enabled_value); -}; - -class HotwordPrivateGetAudioHistoryEnabledFunction - : public ChromeAsyncExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.getAudioHistoryEnabled", - HOTWORDPRIVATE_GETAUDIOHISTORYENABLED) - - protected: - ~HotwordPrivateGetAudioHistoryEnabledFunction() override {} - - // ExtensionFunction: - bool RunAsync() override; - - void SetResultAndSendResponse(bool success, bool new_enabled_value); -}; - -class HotwordPrivateSpeakerModelExistsResultFunction - : public UIThreadExtensionFunction { - public: - DECLARE_EXTENSION_FUNCTION("hotwordPrivate.speakerModelExistsResult", - HOTWORDPRIVATE_SPEAKERMODELEXISTSRESULT) - - protected: - ~HotwordPrivateSpeakerModelExistsResultFunction() override {} - - // ExtensionFunction: - ResponseAction Run() override; -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_HOTWORD_PRIVATE_HOTWORD_PRIVATE_API_H_ diff --git a/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc b/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc deleted file mode 100644 index 4ef4e4ba211f4..0000000000000 --- a/chrome/browser/extensions/api/hotword_private/hotword_private_apitest.cc +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "base/command_line.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/history/web_history_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_client.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" -#include "components/signin/core/browser/profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" -#include "extensions/common/switches.h" -#include "extensions/test/extension_test_message_listener.h" -#include "net/traffic_annotation/network_traffic_annotation_test_helper.h" -#include "net/url_request/url_request_context_getter.h" - -namespace { - -const char kHotwordTestExtensionId[] = "cpfhkdbjfdgdebcjlifoldbijinjfifp"; - -// Mock the web history service so that we don't make actual requests over the -// network. -class MockWebHistoryService : public history::WebHistoryService { - public: - explicit MockWebHistoryService(Profile* profile) - : WebHistoryService( - ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - SigninManagerFactory::GetForProfile(profile), - profile->GetRequestContext()), - expected_success_(true), - expected_value_(false) {} - ~MockWebHistoryService() override {} - - // For both of the following functions, just call the callback to simulate - // a successful return from the url fetch. - void GetAudioHistoryEnabled(const AudioWebHistoryCallback& callback, - const net::PartialNetworkTrafficAnnotationTag& - partial_traffic_annotation) override { - callback.Run(expected_success_, expected_value_ && expected_success_); - } - - void SetAudioHistoryEnabled(bool new_enabled_value, - const AudioWebHistoryCallback& callback, - const net::PartialNetworkTrafficAnnotationTag& - partial_traffic_annotation) override { - callback.Run(expected_success_, new_enabled_value && expected_success_); - } - - void SetExpectedValue(bool expected_value) { - expected_value_ = expected_value; - } - - void SetFailureState() { - expected_success_ = false; - } - - private: - bool expected_success_; - bool expected_value_; -}; - -// Make a mock audio history handler so that the method for getting the web -// history can be overridden. -class MockAudioHistoryHandler : public HotwordAudioHistoryHandler { - public: - MockAudioHistoryHandler(content::BrowserContext* context, - history::WebHistoryService* web_history) - : HotwordAudioHistoryHandler(context, - base::ThreadTaskRunnerHandle::Get()), - web_history_(web_history) {} - ~MockAudioHistoryHandler() override {} - - history::WebHistoryService* GetWebHistory() override { - return web_history_.get(); - } - - private: - std::unique_ptr web_history_; -}; - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), service_available_(true) {} - ~MockHotwordService() override {} - - bool IsServiceAvailable() override { return service_available_; } - - void setServiceAvailable(bool available) { - service_available_ = available; - } - - static std::unique_ptr Build(content::BrowserContext* profile) { - return base::MakeUnique(static_cast(profile)); - } - - LaunchMode GetHotwordAudioVerificationLaunchMode() override { - return launch_mode_; - } - - void SetHotwordAudioVerificationLaunchMode(const LaunchMode& launch_mode) { - launch_mode_ = launch_mode; - } - - private: - bool service_available_; - LaunchMode launch_mode_; - - DISALLOW_COPY_AND_ASSIGN(MockHotwordService); -}; - -class MockHotwordClient : public HotwordClient { - public: - MockHotwordClient() - : last_enabled_(false), - state_changed_count_(0), - recognized_count_(0) { - } - - ~MockHotwordClient() override {} - - void OnHotwordStateChanged(bool enabled) override { - last_enabled_ = enabled; - state_changed_count_++; - } - - void OnHotwordRecognized( - const scoped_refptr& preamble) - override { recognized_count_++; } - - bool last_enabled() const { return last_enabled_; } - int state_changed_count() const { return state_changed_count_; } - int recognized_count() const { return recognized_count_; } - - private: - bool last_enabled_; - int state_changed_count_; - int recognized_count_; - - DISALLOW_COPY_AND_ASSIGN(MockHotwordClient); -}; - -class HotwordPrivateApiTest : public ExtensionApiTest { - public: - HotwordPrivateApiTest() {} - ~HotwordPrivateApiTest() override {} - - void SetUpCommandLine(base::CommandLine* command_line) override { - ExtensionApiTest::SetUpCommandLine(command_line); - - // Whitelist the test extensions (which all share a common ID) to use - // private APIs. - command_line->AppendSwitchASCII( - extensions::switches::kWhitelistedExtensionID, kHotwordTestExtensionId); - } - - void SetUpOnMainThread() override { - ExtensionApiTest::SetUpOnMainThread(); - - test_data_dir_ = test_data_dir_.AppendASCII("hotword_private"); - - service_ = static_cast( - HotwordServiceFactory::GetInstance()->SetTestingFactoryAndUse( - profile(), MockHotwordService::Build)); - } - - MockHotwordService* service() { - return service_; - } - - private: - MockHotwordService* service_; - - DISALLOW_COPY_AND_ASSIGN(HotwordPrivateApiTest); -}; - -} // anonymous namespace - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetEnabled) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setEnabledTrue")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setEnabledFalse")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetAudioLoggingEnabled) { - EXPECT_FALSE(service()->IsOptedIntoAudioLogging()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setAudioLoggingEnableTrue")) - << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - EXPECT_TRUE(service()->IsOptedIntoAudioLogging()); - - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setAudioLoggingEnableFalse")) - << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)); - EXPECT_FALSE(service()->IsOptedIntoAudioLogging()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SetHotwordAlwaysOnSearchEnabled) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE(RunComponentExtensionTest("setHotwordAlwaysOnSearchEnableTrue")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - listener.Reset(); - ASSERT_TRUE(RunComponentExtensionTest("setHotwordAlwaysOnSearchEnableFalse")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, GetStatus) { - ASSERT_TRUE(RunComponentExtensionTest("getEnabled")) << message_; -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableTrue) { - service()->setServiceAvailable(true); - ExtensionTestMessageListener listener("available: true", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailable")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableTrue_NoGet) { - service()->setServiceAvailable(true); - ExtensionTestMessageListener listener("available: false", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailableNoGet")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, IsAvailableFalse) { - service()->setServiceAvailable(false); - ExtensionTestMessageListener listener("available: false", false); - ASSERT_TRUE(RunComponentExtensionTest("isAvailable")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AlwaysOnEnabled) { - // Bypass the hotword hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - { - ExtensionTestMessageListener listener("alwaysOnEnabled: false", - false); - ASSERT_TRUE(RunComponentExtensionTest("alwaysOnEnabled")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } - - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - { - ExtensionTestMessageListener listener("alwaysOnEnabled: true", - false); - ASSERT_TRUE(RunComponentExtensionTest("alwaysOnEnabled")) - << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnEnabledChanged) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII("onEnabledChanged"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); - - listenerNotification.Reset(); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - true); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); - - listenerNotification.Reset(); - service()->StartTraining(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, HotwordSession) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - LoadExtensionAsComponent( - test_data_dir_.AppendASCII("hotwordSession")); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerStopReady("stopReady", false); - ExtensionTestMessageListener listenerStopped("stopped", false); - MockHotwordClient client; - service()->RequestHotwordSession(&client); - EXPECT_TRUE(listenerStopReady.WaitUntilSatisfied()); - service()->StopHotwordSession(&client); - EXPECT_TRUE(listenerStopped.WaitUntilSatisfied()); - - EXPECT_TRUE(client.last_enabled()); - EXPECT_EQ(1, client.state_changed_count()); - EXPECT_EQ(1, client.recognized_count()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, GetLaunchStateHotwordOnly) { - service()->SetHotwordAudioVerificationLaunchMode( - HotwordService::HOTWORD_ONLY); - ExtensionTestMessageListener listener("launchMode: 0", false); - ASSERT_TRUE(RunComponentExtensionTest("getLaunchState")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, - GetLaunchStateHotwordAudioHistory) { - service()->SetHotwordAudioVerificationLaunchMode( - HotwordService::HOTWORD_AND_AUDIO_HISTORY); - ExtensionTestMessageListener listener("launchMode: 1", false); - ASSERT_TRUE(RunComponentExtensionTest("getLaunchState")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnFinalizeSpeakerModel) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onFinalizeSpeakerModel"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - service()->FinalizeSpeakerModel(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnHotwordTriggered) { - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onHotwordTriggered"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - service()->NotifyHotwordTriggered(); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -#if defined(OS_LINUX) -#define MAYBE_OnDeleteSpeakerModel DISABLED_OnDeleteSpeakerModel -#else -#define MAYBE_OnDeleteSpeakerModel OnDeleteSpeakerModel -#endif -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, MAYBE_OnDeleteSpeakerModel) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetExpectedValue(false); - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - // Trigger the pref registrar. - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onDeleteSpeakerModel"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, OnSpeakerModelExists) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onSpeakerModelExists"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - service()->OptIntoHotwording(HotwordService::HOTWORD_ONLY); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, SpeakerModelExistsResult) { - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - ExtensionTestMessageListener listenerTrue("ready", false); - ASSERT_TRUE(RunComponentExtensionTest( - "speakerModelExistsResultTrue")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); - - PrefService* prefs = profile()->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, false); - ExtensionTestMessageListener listenerFalse("ready", false); - ASSERT_TRUE(RunComponentExtensionTest( - "speakerModelExistsResultFalse")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(profile()->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnSearchEnabled)); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, Training) { - EXPECT_FALSE(service()->IsTraining()); - - ExtensionTestMessageListener listenerTrue("start training", false); - ASSERT_TRUE(RunComponentExtensionTest("startTraining")) << message_; - EXPECT_TRUE(listenerTrue.WaitUntilSatisfied()); - EXPECT_TRUE(service()->IsTraining()); - - ExtensionTestMessageListener listenerFalse("stop training", false); - ASSERT_TRUE(RunComponentExtensionTest("stopTraining")) << message_; - EXPECT_TRUE(listenerFalse.WaitUntilSatisfied()); - EXPECT_FALSE(service()->IsTraining()); -} - -// Flaky on ChromeOS (https://crbug.com/668335) -#if defined(OS_CHROMEOS) -#define MAYBE_OnSpeakerModelSaved DISABLED_OnSpeakerModelSaved -#else -#define MAYBE_OnSpeakerModelSaved OnSpeakerModelSaved -#endif - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, MAYBE_OnSpeakerModelSaved) { - extensions::HotwordPrivateEventService::GetFactoryInstance(); - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE( - LoadExtensionAsComponent(test_data_dir_.AppendASCII( - "onSpeakerModelSaved"))); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - ExtensionTestMessageListener listenerNotification("notification", false); - EXPECT_TRUE(listenerNotification.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, NotifySpeakerModelSaved) { - ExtensionTestMessageListener listener("speaker model saved", false); - ASSERT_TRUE( - RunComponentExtensionTest("notifySpeakerModelSaved")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistory) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetExpectedValue(true); - - ExtensionTestMessageListener setListenerT("set AH True: true success", false); - ExtensionTestMessageListener setListenerF("set AH False: false success", - false); - ExtensionTestMessageListener getListener("get AH: true success", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); - - web_history->SetExpectedValue(false); - - ExtensionTestMessageListener setListenerT2("set AH True: true success", - false); - ExtensionTestMessageListener setListenerF2("set AH False: false success", - false); - ExtensionTestMessageListener getListener2("get AH: false success", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT2.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF2.WaitUntilSatisfied()); - EXPECT_TRUE(getListener2.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistoryNoWebHistory) { - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), nullptr); - service()->SetAudioHistoryHandler(handler); - - // Set an initial value for the audio logging pref. - PrefService* prefs = profile()->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, true); - - ExtensionTestMessageListener setListenerT("set AH True: true failure", false); - ExtensionTestMessageListener setListenerF("set AH False: true failure", - false); - ExtensionTestMessageListener getListener("get AH: true failure", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); -} - -IN_PROC_BROWSER_TEST_F(HotwordPrivateApiTest, AudioHistoryWebHistoryFailure) { - MockWebHistoryService* web_history = new MockWebHistoryService(profile()); - MockAudioHistoryHandler* handler = - new MockAudioHistoryHandler(profile(), web_history); - service()->SetAudioHistoryHandler(handler); - web_history->SetFailureState(); - // It shouldn't matter if this is set to true. GetAudioHistoryEnabled should - // still return false. - web_history->SetExpectedValue(true); - - ExtensionTestMessageListener setListenerT("set AH True: true failure", false); - ExtensionTestMessageListener setListenerF("set AH False: false failure", - false); - ExtensionTestMessageListener getListener("get AH: false failure", false); - - ASSERT_TRUE(RunComponentExtensionTest("audioHistory")) << message_; - - EXPECT_TRUE(setListenerT.WaitUntilSatisfied()); - EXPECT_TRUE(setListenerF.WaitUntilSatisfied()); - EXPECT_TRUE(getListener.WaitUntilSatisfied()); -} diff --git a/chrome/browser/extensions/api/preference/preference_api.cc b/chrome/browser/extensions/api/preference/preference_api.cc index b388308c6484c..153c8f78eda7d 100644 --- a/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chrome/browser/extensions/api/preference/preference_api.cc @@ -102,8 +102,6 @@ const PrefMappingEntry kPrefMapping[] = { APIPermission::kPrivacy, APIPermission::kPrivacy}, {"hyperlinkAuditingEnabled", prefs::kEnableHyperlinkAuditing, APIPermission::kPrivacy, APIPermission::kPrivacy}, - {"hotwordSearchEnabled", prefs::kHotwordSearchEnabled, - APIPermission::kPrivacy, APIPermission::kPrivacy}, {"networkPredictionEnabled", prefs::kNetworkPredictionOptions, APIPermission::kPrivacy, APIPermission::kPrivacy}, {"passwordSavingEnabled", diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index 2c0ae37715677..7b73936b86004 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -426,12 +426,6 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_private::PrefType::PREF_TYPE_BOOLEAN; #endif - // Search settings. - (*s_whitelist)[::prefs::kHotwordSearchEnabled] = - settings_private::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[::prefs::kHotwordAlwaysOnSearchEnabled] = - settings_private::PrefType::PREF_TYPE_BOOLEAN; - // Proxy settings. (*s_whitelist)[proxy_config::prefs::kProxy] = settings_private::PrefType::PREF_TYPE_DICTIONARY; diff --git a/chrome/browser/extensions/browser_context_keyed_service_factories.cc b/chrome/browser/extensions/browser_context_keyed_service_factories.cc index 2403fc0fcaecc..0ff6f15fc3781 100644 --- a/chrome/browser/extensions/browser_context_keyed_service_factories.cc +++ b/chrome/browser/extensions/browser_context_keyed_service_factories.cc @@ -20,7 +20,6 @@ #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/api/font_settings/font_settings_api.h" #include "chrome/browser/extensions/api/history/history_api.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" #include "chrome/browser/extensions/api/identity/identity_api.h" #include "chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h" #include "chrome/browser/extensions/api/omnibox/omnibox_api.h" @@ -94,7 +93,6 @@ void EnsureBrowserContextKeyedServiceFactoriesBuilt() { extensions::ExtensionWebUIOverrideRegistrar::GetFactoryInstance(); extensions::FontSettingsAPI::GetFactoryInstance(); extensions::HistoryAPI::GetFactoryInstance(); - extensions::HotwordPrivateEventService::GetFactoryInstance(); extensions::IdentityAPI::GetFactoryInstance(); extensions::InstallTrackerFactory::GetInstance(); extensions::InstallVerifierFactory::GetInstance(); diff --git a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc index c81399a35a32e..d8a82a2216cb1 100644 --- a/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc +++ b/chrome/browser/extensions/component_extensions_whitelist/whitelist.cc @@ -26,7 +26,6 @@ namespace extensions { bool IsComponentExtensionWhitelisted(const std::string& extension_id) { const char* const kAllowed[] = { - extension_misc::kHotwordSharedModuleId, extension_misc::kInAppPaymentsSupportAppId, extension_misc::kMediaRouterStableExtensionId, extension_misc::kPdfExtensionId, @@ -72,10 +71,6 @@ bool IsComponentExtensionWhitelisted(int manifest_resource_id) { case IDR_GAIA_AUTH_MANIFEST: #if BUILDFLAG(ENABLE_HANGOUT_SERVICES_EXTENSION) case IDR_HANGOUT_SERVICES_MANIFEST: -#endif -#if defined(ENABLE_HOTWORDING) - case IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST: - case IDR_HOTWORD_MANIFEST: #endif case IDR_IDENTITY_API_SCOPE_APPROVAL_MANIFEST: #if defined(OS_CHROMEOS) diff --git a/chrome/browser/extensions/component_loader.cc b/chrome/browser/extensions/component_loader.cc index d6a3a47b53b7f..7b8e2be3a0873 100644 --- a/chrome/browser/extensions/component_loader.cc +++ b/chrome/browser/extensions/component_loader.cc @@ -19,8 +19,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/pdf/pdf_extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/ui/webui/md_bookmarks/md_bookmarks_ui.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_paths.h" @@ -356,24 +354,6 @@ void ComponentLoader::AddHangoutServicesExtension() { #endif } -void ComponentLoader::AddHotwordAudioVerificationApp() { -#if defined(ENABLE_HOTWORDING) - if (HotwordServiceFactory::IsAlwaysOnAvailable()) { - Add(IDR_HOTWORD_AUDIO_VERIFICATION_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("hotword_audio_verification"))); - } -#endif -} - -void ComponentLoader::AddHotwordHelperExtension() { -#if defined(ENABLE_HOTWORDING) - if (HotwordServiceFactory::IsHotwordAllowed(profile_)) { - Add(IDR_HOTWORD_MANIFEST, - base::FilePath(FILE_PATH_LITERAL("hotword"))); - } -#endif -} - void ComponentLoader::AddImageLoaderExtension() { #if defined(OS_CHROMEOS) Add(IDR_IMAGE_LOADER_MANIFEST, @@ -580,8 +560,6 @@ void ComponentLoader::AddDefaultComponentExtensionsWithBackgroundPages( AddWebstoreWidgetExtension(); AddHangoutServicesExtension(); - AddHotwordAudioVerificationApp(); - AddHotwordHelperExtension(); AddImageLoaderExtension(); bool install_feedback = enable_background_extensions_during_testing; diff --git a/chrome/browser/extensions/component_loader.h b/chrome/browser/extensions/component_loader.h index 6cb9596cd4622..3416f5696dfb1 100644 --- a/chrome/browser/extensions/component_loader.h +++ b/chrome/browser/extensions/component_loader.h @@ -168,7 +168,6 @@ class ComponentLoader { void AddZipArchiverExtension(); void AddWebstoreWidgetExtension(); void AddHangoutServicesExtension(); - void AddHotwordHelperExtension(); void AddImageLoaderExtension(); void AddNetworkSpeechSynthesisExtension(); @@ -177,7 +176,6 @@ class ComponentLoader { const std::string& name_string, const std::string& description_string); void AddChromeApp(); - void AddHotwordAudioVerificationApp(); void AddKeyboardApp(); void AddWebStoreApp(); diff --git a/chrome/browser/extensions/external_component_loader.cc b/chrome/browser/extensions/external_component_loader.cc index 8768741e062a7..27b103ff1d60e 100644 --- a/chrome/browser/extensions/external_component_loader.cc +++ b/chrome/browser/extensions/external_component_loader.cc @@ -9,8 +9,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/component_extensions_whitelist/whitelist.h" #include "chrome/browser/media/router/media_router_feature.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/features.h" @@ -20,7 +18,6 @@ #include "extensions/common/manifest.h" #if defined(OS_CHROMEOS) -#include "base/command_line.h" #include "chromeos/chromeos_switches.h" #endif @@ -38,9 +35,6 @@ void ExternalComponentLoader::StartLoading() { AddExternalExtension(extension_misc::kInAppPaymentsSupportAppId, prefs.get()); #endif // defined(GOOGLE_CHROME_BUILD) - if (HotwordServiceFactory::IsHotwordAllowed(profile_)) - AddExternalExtension(extension_misc::kHotwordSharedModuleId, prefs.get()); - #if defined(OS_CHROMEOS) { base::CommandLine* const command_line = diff --git a/chrome/browser/extensions/hotword_browsertest.cc b/chrome/browser/extensions/hotword_browsertest.cc deleted file mode 100644 index 076a4556a0ce5..0000000000000 --- a/chrome/browser/extensions/hotword_browsertest.cc +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/file_path.h" -#include "base/macros.h" -#include "chrome/browser/extensions/component_loader.h" -#include "chrome/browser/extensions/error_console/error_console.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/prefs/pref_service.h" -#include "content/public/common/content_switches.h" -#include "extensions/common/extension.h" -#include "extensions/test/extension_test_message_listener.h" -#include "testing/gtest/include/gtest/gtest.h" - - -namespace extensions { - -static const char kHotwordHelperExtensionId[] = - "dnhpdliibojhegemfjheidglijccjfmc"; - -class HotwordBrowserTest : public ExtensionBrowserTest { - public: - HotwordBrowserTest() : error_console_(NULL) { } - ~HotwordBrowserTest() override {} - - protected: - void SetUpInProcessBrowserTestFixture() override { - ExtensionBrowserTest::SetUpInProcessBrowserTestFixture(); - - // Load the hotword_helper extension. - ComponentLoader::EnableBackgroundExtensionsForTesting(); - - // We need to enable the ErrorConsole FeatureSwitch in order to collect - // errors. This should be enabled on any channel <= Dev, but let's make - // sure (in case a test is running on, e.g., a beta channel). - FeatureSwitch::error_console()->SetOverrideValue( - FeatureSwitch::OVERRIDE_ENABLED); - } - - void SetUpOnMainThread() override { - ExtensionBrowserTest::SetUpOnMainThread(); - - // Errors are only kept if we have Developer Mode enabled. - profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true); - - error_console_ = ErrorConsole::Get(profile()); - ASSERT_TRUE(error_console_); - } - - ErrorConsole* error_console() { return error_console_; } - - private: - // Weak reference to the ErrorConsole. - ErrorConsole* error_console_; - - DISALLOW_COPY_AND_ASSIGN(HotwordBrowserTest); -}; - -// Test we silently capture an exception from a message handler's response -// callback. This happens when the caller to chrome.runtime.sendMessage() -// doesn't specify a response callback. -// NOTE(amistry): Test is disabled instead of deleted since the functionality -// may still be required to implement crbug.com/436681 -IN_PROC_BROWSER_TEST_F(HotwordBrowserTest, DISABLED_MessageSendResponseError) { - // Enable error reporting for the hotword helper extension. - error_console()->SetReportingAllForExtension(kHotwordHelperExtensionId, true); - - ExtensionTestMessageListener doneListener("done", false); - const Extension* extension = extension_service()->GetExtensionById( - kHotwordHelperExtensionId, false); - ASSERT_TRUE(extension); - const Extension* test_extension = LoadExtension( - test_data_dir_.AppendASCII("hotword")); - ASSERT_TRUE(test_extension); - - ASSERT_TRUE(doneListener.WaitUntilSatisfied()); - ASSERT_TRUE(error_console()->GetErrorsForExtension(extension->id()).empty()); -} - -} // namespace extensions diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 95ef64f119df4..f93080914f709 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc @@ -580,12 +580,6 @@ const char kExperimentalFullscreenExitUIDescription[] = "Displays experimental UI to allow mouse and touch input methods to exit " "fullscreen mode."; -const char kExperimentalHotwordHardwareName[] = - "Simulated hardware 'Ok Google' features"; -const char kExperimentalHotwordHardwareDescription[] = - "Enables an experimental version of 'Ok Google' hotword detection features " - "that have a hardware dependency."; - const char kExperimentalKeyboardLockUiName[] = "Experimental keyboard lock UI."; const char kExperimentalKeyboardLockUiDescription[] = "An experimental full screen with keyboard lock mode requiring users to " diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 0050a38df623e..95e9370bdd31d 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h @@ -372,9 +372,6 @@ extern const char kExperimentalExtensionApisDescription[]; extern const char kExperimentalFullscreenExitUIName[]; extern const char kExperimentalFullscreenExitUIDescription[]; -extern const char kExperimentalHotwordHardwareName[]; -extern const char kExperimentalHotwordHardwareDescription[]; - extern const char kExperimentalKeyboardLockUiName[]; extern const char kExperimentalKeyboardLockUiDescription[]; diff --git a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc index bebf5ea9d5b8d..4b723cbe6ae05 100644 --- a/chrome/browser/media/webrtc/media_stream_capture_indicator.cc +++ b/chrome/browser/media/webrtc/media_stream_capture_indicator.cc @@ -61,20 +61,6 @@ const extensions::Extension* GetExtension(WebContents* web_contents) { web_contents->GetURL()); } -bool IsWhitelistedExtension(const extensions::Extension* extension) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - - static const char* const kExtensionWhitelist[] = { - extension_misc::kHotwordNewExtensionId, - }; - - for (size_t i = 0; i < arraysize(kExtensionWhitelist); ++i) { - if (extension->id() == kExtensionWhitelist[i]) - return true; - } - - return false; -} #endif // BUILDFLAG(ENABLE_EXTENSIONS) base::string16 GetTitle(WebContents* web_contents) { @@ -392,7 +378,7 @@ void MediaStreamCaptureIndicator::UpdateNotificationUserInterface() { // icon. #if BUILDFLAG(ENABLE_EXTENSIONS) const extensions::Extension* extension = GetExtension(web_contents); - if (!extension || IsWhitelistedExtension(extension)) + if (!extension) continue; #endif diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index f78f58bbfb2e2..0e49fc2780917 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc @@ -91,7 +91,6 @@ #include "chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h" #include "chrome/browser/extensions/browser_context_keyed_service_factories.h" #include "chrome/browser/extensions/extension_management.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/signin/easy_unlock_service_factory.h" #include "chrome/browser/ui/bookmarks/enhanced_bookmark_key_service_factory.h" #include "extensions/browser/api/networking_private/networking_private_delegate_factory.h" @@ -255,9 +254,6 @@ EnsureBrowserContextKeyedServiceFactoriesBuilt() { #endif GoogleURLTrackerFactory::GetInstance(); HistoryServiceFactory::GetInstance(); -#if BUILDFLAG(ENABLE_EXTENSIONS) - HotwordServiceFactory::GetInstance(); -#endif HostContentSettingsMapFactory::GetInstance(); InMemoryURLIndexFactory::GetInstance(); invalidation::ProfileInvalidationProviderFactory::GetInstance(); diff --git a/chrome/browser/resources/component_extension_resources.grd b/chrome/browser/resources/component_extension_resources.grd index 73e3f9f7fc495..60df4347af72c 100644 --- a/chrome/browser/resources/component_extension_resources.grd +++ b/chrome/browser/resources/component_extension_resources.grd @@ -13,7 +13,6 @@ - @@ -48,49 +47,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/chrome/browser/resources/hotword/OWNERS b/chrome/browser/resources/hotword/OWNERS deleted file mode 100644 index 2ae98b3a1f11e..0000000000000 --- a/chrome/browser/resources/hotword/OWNERS +++ /dev/null @@ -1,2 +0,0 @@ -kcarattini@chromium.org -mgiuca@chromium.org diff --git a/chrome/browser/resources/hotword/always_on_manager.js b/chrome/browser/resources/hotword/always_on_manager.js deleted file mode 100644 index f34bc6da3709a..0000000000000 --- a/chrome/browser/resources/hotword/always_on_manager.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage always-on hotwording. Automatically starts hotwording - * on startup, if always-on is enabled, and starts/stops hotwording at - * appropriate times. - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function AlwaysOnManager(stateManager) { - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.ALWAYS); - } - - AlwaysOnManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isAlwaysOnEnabled(); - }, - - /** @override */ - updateListeners: function() { - hotword.BaseSessionManager.prototype.updateListeners.call(this); - if (this.enabled()) - this.startSession(); - } - }; - - return {AlwaysOnManager: AlwaysOnManager}; -}); diff --git a/chrome/browser/resources/hotword/audio_client.js b/chrome/browser/resources/hotword/audio_client.js deleted file mode 100644 index 552dd49cdafff..0000000000000 --- a/chrome/browser/resources/hotword/audio_client.js +++ /dev/null @@ -1,375 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -'use strict'; - -/* eslint-disable no-restricted-properties */ - -/** - * @fileoverview This is the audio client content script injected into eligible - * Google.com and New tab pages for interaction between the Webpage and the - * Hotword extension. - */ - -(function() { -/** - * @constructor - */ -var AudioClient = function() { - /** @private {Element} */ - this.speechOverlay_ = null; - - /** @private {number} */ - this.checkSpeechUiRetries_ = 0; - - /** - * Port used to communicate with the audio manager. - * @private {?Port} - */ - this.port_ = null; - - /** - * Keeps track of the effects of different commands. Used to verify that - * proper UIs are shown to the user. - * @private {Object} - */ - this.uiStatus_ = null; - - /** - * Bound function used to handle commands sent from the page to this script. - * @private {Function} - */ - this.handleCommandFromPageFunc_ = null; -}; - -/** - * Messages sent to the page to control the voice search UI. - * @enum {string} - */ -AudioClient.CommandToPage = { - HOTWORD_VOICE_TRIGGER: 'vt', - HOTWORD_STARTED: 'hs', - HOTWORD_ENDED: 'hd', - HOTWORD_TIMEOUT: 'ht', - HOTWORD_ERROR: 'he' -}; - -/** - * Messages received from the page used to indicate voice search state. - * @enum {string} - */ -AudioClient.CommandFromPage = { - SPEECH_START: 'ss', - SPEECH_END: 'se', - SPEECH_RESET: 'sr', - SHOWING_HOTWORD_START: 'shs', - SHOWING_ERROR_MESSAGE: 'sem', - SHOWING_TIMEOUT_MESSAGE: 'stm', - CLICKED_RESUME: 'hcc', - CLICKED_RESTART: 'hcr', - CLICKED_DEBUG: 'hcd' -}; - -/** - * Errors that are sent to the hotword extension. - * @enum {string} - */ -AudioClient.Error = { - NO_SPEECH_UI: 'ac1', - NO_HOTWORD_STARTED_UI: 'ac2', - NO_HOTWORD_TIMEOUT_UI: 'ac3', - NO_HOTWORD_ERROR_UI: 'ac4' -}; - -/** - * @const {string} - * @private - */ -AudioClient.HOTWORD_EXTENSION_ID_ = 'nbpagnldghgfoolbancepceaanlmhfmd'; - -/** - * Number of times to retry checking a transient error. - * @const {number} - * @private - */ -AudioClient.MAX_RETRIES = 3; - -/** - * Delay to wait in milliseconds before rechecking for any transient errors. - * @const {number} - * @private - */ -AudioClient.RETRY_TIME_MS_ = 2000; - -/** - * DOM ID for the speech UI overlay. - * @const {string} - * @private - */ -AudioClient.SPEECH_UI_OVERLAY_ID_ = 'spch'; - -/** - * @const {string} - * @private - */ -AudioClient.HELP_CENTER_URL_ = - 'https://support.google.com/chrome/?p=ui_hotword_search'; - -/** - * @const {string} - * @private - */ -AudioClient.CLIENT_PORT_NAME_ = 'chwcpn'; - -/** - * Existence of the Audio Client. - * @const {string} - * @private - */ -AudioClient.EXISTS_ = 'chwace'; - -/** - * Checks for the presence of speech overlay UI DOM elements. - * @private - */ -AudioClient.prototype.checkSpeechOverlayUi_ = function() { - if (!this.speechOverlay_) { - window.setTimeout( - this.delayedCheckSpeechOverlayUi_.bind(this), - AudioClient.RETRY_TIME_MS_); - } else { - this.checkSpeechUiRetries_ = 0; - } -}; - -/** - * Function called to check for the speech UI overlay after some time has - * passed since an initial check. Will either retry triggering the speech - * or sends an error message depending on the number of retries. - * @private - */ -AudioClient.prototype.delayedCheckSpeechOverlayUi_ = function() { - this.speechOverlay_ = - document.getElementById(AudioClient.SPEECH_UI_OVERLAY_ID_); - if (!this.speechOverlay_) { - if (this.checkSpeechUiRetries_++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(AudioClient.CommandToPage.VOICE_TRIGGER); - this.checkSpeechOverlayUi_(); - } else { - this.sendCommandToExtension_(AudioClient.Error.NO_SPEECH_UI); - } - } else { - this.checkSpeechUiRetries_ = 0; - } -}; - -/** - * Checks that the triggered UI is actually displayed. - * @param {AudioClient.CommandToPage} command Command that was send. - * @private - */ -AudioClient.prototype.checkUi_ = function(command) { - this.uiStatus_[command].timeoutId = window.setTimeout( - this.failedCheckUi_.bind(this, command), AudioClient.RETRY_TIME_MS_); -}; - -/** - * Function called when the UI verification is not called in time. Will either - * retry the command or sends an error message, depending on the number of - * retries for the command. - * @param {AudioClient.CommandToPage} command Command that was sent. - * @private - */ -AudioClient.prototype.failedCheckUi_ = function(command) { - if (this.uiStatus_[command].tries++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(command); - this.checkUi_(command); - } else { - this.sendCommandToExtension_(this.uiStatus_[command].error); - } -}; - -/** - * Confirm that an UI element has been shown. - * @param {AudioClient.CommandToPage} command UI to confirm. - * @private - */ -AudioClient.prototype.verifyUi_ = function(command) { - if (this.uiStatus_[command].timeoutId) { - window.clearTimeout(this.uiStatus_[command].timeoutId); - this.uiStatus_[command].timeoutId = null; - this.uiStatus_[command].tries = 0; - } -}; - -/** - * Sends a command to the audio manager. - * @param {string} commandStr command to send to plugin. - * @private - */ -AudioClient.prototype.sendCommandToExtension_ = function(commandStr) { - if (this.port_) - this.port_.postMessage({'cmd': commandStr}); -}; - -/** - * Handles a message from the audio manager. - * @param {{cmd: string}} commandObj Command from the audio manager. - * @private - */ -AudioClient.prototype.handleCommandFromExtension_ = function(commandObj) { - var command = commandObj['cmd']; - if (command) { - switch (command) { - case AudioClient.CommandToPage.HOTWORD_VOICE_TRIGGER: - this.sendCommandToPage_(command); - this.checkSpeechOverlayUi_(); - break; - case AudioClient.CommandToPage.HOTWORD_STARTED: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ENDED: - this.sendCommandToPage_(command); - break; - case AudioClient.CommandToPage.HOTWORD_TIMEOUT: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ERROR: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - } - } -}; - -/** - * @param {AudioClient.CommandToPage} commandStr Command to send. - * @private - */ -AudioClient.prototype.sendCommandToPage_ = function(commandStr) { - window.postMessage({'type': commandStr}, '*'); -}; - -/** - * Handles a message from the html window. - * @param {!MessageEvent} messageEvent Message event from the window. - * @private - */ -AudioClient.prototype.handleCommandFromPage_ = function(messageEvent) { - if (messageEvent.source == window && messageEvent.data.type) { - var command = messageEvent.data.type; - switch (command) { - case AudioClient.CommandFromPage.SPEECH_START: - this.speechActive_ = true; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_END: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_RESET: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case 'SPEECH_RESET': // Legacy, for embedded NTP. - this.speechActive_ = false; - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_END); - break; - case AudioClient.CommandFromPage.CLICKED_RESUME: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_RESTART: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_DEBUG: - window.open(AudioClient.HELP_CENTER_URL_, '_blank'); - break; - case AudioClient.CommandFromPage.SHOWING_HOTWORD_START: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_STARTED); - break; - case AudioClient.CommandFromPage.SHOWING_ERROR_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_ERROR); - break; - case AudioClient.CommandFromPage.SHOWING_TIMEOUT_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_TIMEOUT); - break; - } - } -}; - -/** - * Initialize the content script. - */ -AudioClient.prototype.initialize = function() { - if (AudioClient.EXISTS_ in window) - return; - window[AudioClient.EXISTS_] = true; - - // UI verification object. - this.uiStatus_ = {}; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_STARTED] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_STARTED_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_TIMEOUT] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_TIMEOUT_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_ERROR] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_ERROR_UI - }; - - this.handleCommandFromPageFunc_ = this.handleCommandFromPage_.bind(this); - window.addEventListener('message', this.handleCommandFromPageFunc_, false); - this.initPort_(); -}; - -/** - * Initialize the communications port with the audio manager. This - * function will be also be called again if the audio-manager - * disconnects for some reason (such as the extension - * background.html page being reloaded). - * @private - */ -AudioClient.prototype.initPort_ = function() { - this.port_ = chrome.runtime.connect( - AudioClient.HOTWORD_EXTENSION_ID_, - {'name': AudioClient.CLIENT_PORT_NAME_}); - // Note that this listen may have to be destroyed manually if AudioClient - // is ever destroyed on this tab. - this.port_.onDisconnect.addListener( - (function(e) { - if (this.handleCommandFromPageFunc_) { - window.removeEventListener( - 'message', this.handleCommandFromPageFunc_, false); - } - delete window[AudioClient.EXISTS_]; - }).bind(this)); - - // See note above. - this.port_.onMessage.addListener(this.handleCommandFromExtension_.bind(this)); - - if (this.speechActive_) { - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_START); - } else { - // It's possible for this script to be injected into the page after it has - // completed loaded (i.e. when prerendering). In this case, this script - // won't receive a SPEECH_RESET from the page to forward onto the - // extension. To make up for this, always send a SPEECH_RESET. This means - // in most cases, the extension will receive SPEECH_RESET twice, one from - // this sendCommandToExtension_ and the one forwarded from the page. But - // that's OK and the extension can handle it. - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_RESET); - } -}; - -// Initializes as soon as the code is ready, do not wait for the page. -new AudioClient().initialize(); -})(); diff --git a/chrome/browser/resources/hotword/base_session_manager.js b/chrome/browser/resources/hotword/base_session_manager.js deleted file mode 100644 index 6891199d9a53a..0000000000000 --- a/chrome/browser/resources/hotword/base_session_manager.js +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Base class for managing hotwording sessions. - * @param {!hotword.StateManager} stateManager Manager of global hotwording - * state. - * @param {!hotword.constants.SessionSource} sessionSource Source of the - * hotword session request. - * @constructor - */ - function BaseSessionManager(stateManager, sessionSource) { - /** - * Manager of global hotwording state. - * @protected {!hotword.StateManager} - */ - this.stateManager = stateManager; - - /** - * Source of the hotword session request. - * @private {!hotword.constants.SessionSource} - */ - this.sessionSource_ = sessionSource; - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.sessionRequestedListener_ = this.handleSessionRequested_.bind(this); - this.sessionStoppedListener_ = this.handleSessionStopped_.bind(this); - - // Need to setup listeners on startup, otherwise events that caused the - // event page to start up, will be lost. - this.setupListeners_(); - - this.stateManager.onStatusChanged.addListener(function() { - hotword.debug('onStatusChanged'); - this.updateListeners(); - }.bind(this)); - } - - BaseSessionManager.prototype = { - /** - * Return whether or not this session type is enabled. - * @protected - * @return {boolean} - */ - enabled: assertNotReached, - - /** - * Called when the hotwording session is stopped. - * @protected - */ - onSessionStop: function() {}, - - /** - * Starts a launcher hotwording session. - * @param {hotword.constants.TrainingMode=} opt_mode The mode to start the - * recognizer in. - */ - startSession: function(opt_mode) { - this.stateManager.startSession(this.sessionSource_, function() { - chrome.hotwordPrivate.setHotwordSessionState(true, function() {}); - }, this.handleHotwordTrigger.bind(this), opt_mode); - }, - - /** - * Stops a launcher hotwording session. - * @private - */ - stopSession_: function() { - this.stateManager.stopSession(this.sessionSource_); - this.onSessionStop(); - }, - - /** - * Handles a hotword triggered event. - * @param {?Object} log Audio log data, if audio logging is enabled. - * @protected - */ - handleHotwordTrigger: function(log) { - hotword.debug('Hotword triggered: ' + this.sessionSource_, log); - chrome.hotwordPrivate.notifyHotwordRecognition( - 'search', log, function() {}); - }, - - /** - * Handles a hotwordPrivate.onHotwordSessionRequested event. - * @private - */ - handleSessionRequested_: function() { - hotword.debug('handleSessionRequested_: ' + this.sessionSource_); - this.startSession(); - }, - - /** - * Handles a hotwordPrivate.onHotwordSessionStopped event. - * @private - */ - handleSessionStopped_: function() { - hotword.debug('handleSessionStopped_: ' + this.sessionSource_); - this.stopSession_(); - }, - - /** - * Set up event listeners. - * @private - */ - setupListeners_: function() { - if (chrome.hotwordPrivate.onHotwordSessionRequested.hasListener( - this.sessionRequestedListener_)) { - return; - } - - chrome.hotwordPrivate.onHotwordSessionRequested.addListener( - this.sessionRequestedListener_); - chrome.hotwordPrivate.onHotwordSessionStopped.addListener( - this.sessionStoppedListener_); - }, - - /** - * Remove event listeners. - * @private - */ - removeListeners_: function() { - chrome.hotwordPrivate.onHotwordSessionRequested.removeListener( - this.sessionRequestedListener_); - chrome.hotwordPrivate.onHotwordSessionStopped.removeListener( - this.sessionStoppedListener_); - }, - - /** - * Update event listeners based on the current hotwording state. - * @protected - */ - updateListeners: function() { - if (this.enabled()) { - this.setupListeners_(); - } else { - this.removeListeners_(); - this.stopSession_(); - } - } - }; - - return {BaseSessionManager: BaseSessionManager}; -}); diff --git a/chrome/browser/resources/hotword/constants.js b/chrome/browser/resources/hotword/constants.js deleted file mode 100644 index 0fbfa0e8a45f2..0000000000000 --- a/chrome/browser/resources/hotword/constants.js +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword.constants', function() { - 'use strict'; - - /** - * Number of seconds of audio to record when logging is enabled. - * @const {number} - */ - var AUDIO_LOG_SECONDS = 2; - - /** - * Timeout in seconds, for detecting false positives with a hotword stream. - * @const {number} - */ - var HOTWORD_STREAM_TIMEOUT_SECONDS = 2; - - /** - * Hotword data shared module extension's ID. - * @const {string} - */ - var SHARED_MODULE_ID = 'lccekmodgklaepjeofjdjpbminllajkg'; - - /** - * Path to shared module data. - * @const {string} - */ - var SHARED_MODULE_ROOT = '_modules/' + SHARED_MODULE_ID; - - /** - * Name used by the content scripts to create communications Ports. - * @const {string} - */ - var CLIENT_PORT_NAME = 'chwcpn'; - - /** - * The field name to specify the command among pages. - * @const {string} - */ - var COMMAND_FIELD_NAME = 'cmd'; - - /** - * The speaker model file name. - * @const {string} - */ - var SPEAKER_MODEL_FILE_NAME = 'speaker_model.data'; - - /** - * The training utterance file name prefix. - * @const {string} - */ - var UTTERANCE_FILE_PREFIX = 'utterance-'; - - /** - * The training utterance file extension. - * @const {string} - */ - var UTTERANCE_FILE_EXTENSION = '.raw'; - - /** - * The number of training utterances required to train the speaker model. - * @const {number} - */ - var NUM_TRAINING_UTTERANCES = 3; - - /** - * The size of the file system requested for reading the speaker model and - * utterances. This number should always be larger than the combined file - * size, - * currently 576338 bytes as of February 2015. - * @const {number} - */ - var FILE_SYSTEM_SIZE_BYTES = 1048576; - - /** - * Time to wait for expected messages, in milliseconds. - * @enum {number} - */ - var TimeoutMs = {SHORT: 200, NORMAL: 500, LONG: 2000}; - - /** - * The URL of the files used by the plugin. - * @enum {string} - */ - var File = { - RECOGNIZER_CONFIG: 'hotword.data', - }; - - /** - * Errors emitted by the NaClManager. - * @enum {string} - */ - var Error = { - NACL_CRASH: 'nacl_crash', - TIMEOUT: 'timeout', - }; - - /** - * Event types supported by NaClManager. - * @enum {string} - */ - var Event = { - READY: 'ready', - TRIGGER: 'trigger', - SPEAKER_MODEL_SAVED: 'speaker model saved', - ERROR: 'error', - TIMEOUT: 'timeout', - }; - - /** - * Messages for communicating with the NaCl recognizer plugin. These must - * match - * constants in /hotword_plugin.c - * @enum {string} - */ - var NaClPlugin = { - RESTART: 'r', - SAMPLE_RATE_PREFIX: 'h', - MODEL_PREFIX: 'm', - STOP: 's', - LOG: 'l', - DSP: 'd', - BEGIN_SPEAKER_MODEL: 'b', - ADAPT_SPEAKER_MODEL: 'a', - FINISH_SPEAKER_MODEL: 'f', - SPEAKER_MODEL_SAVED: 'sm_saved', - REQUEST_MODEL: 'model', - MODEL_LOADED: 'model_loaded', - READY_FOR_AUDIO: 'audio', - STOPPED: 'stopped', - HOTWORD_DETECTED: 'hotword', - MS_CONFIGURED: 'ms_configured', - TIMEOUT: 'timeout' - }; - - /** - * Messages sent from the injected scripts to the Google page. - * @enum {string} - */ - var CommandToPage = { - HOTWORD_VOICE_TRIGGER: 'vt', - HOTWORD_STARTED: 'hs', - HOTWORD_ENDED: 'hd', - HOTWORD_TIMEOUT: 'ht', - HOTWORD_ERROR: 'he' - }; - - /** - * Messages sent from the Google page to the extension or to the - * injected script and then passed to the extension. - * @enum {string} - */ - var CommandFromPage = { - SPEECH_START: 'ss', - SPEECH_END: 'se', - SPEECH_RESET: 'sr', - SHOWING_HOTWORD_START: 'shs', - SHOWING_ERROR_MESSAGE: 'sem', - SHOWING_TIMEOUT_MESSAGE: 'stm', - CLICKED_RESUME: 'hcc', - CLICKED_RESTART: 'hcr', - CLICKED_DEBUG: 'hcd', - WAKE_UP_HELPER: 'wuh', - // Command specifically for the opt-in promo below this line. - // User has explicitly clicked 'no'. - CLICKED_NO_OPTIN: 'hcno', - // User has opted in. - CLICKED_OPTIN: 'hco', - // User clicked on the microphone. - PAGE_WAKEUP: 'wu' - }; - - /** - * Source of a hotwording session request. - * @enum {string} - */ - var SessionSource = { - LAUNCHER: 'launcher', - NTP: 'ntp', - ALWAYS: 'always', - TRAINING: 'training' - }; - - /** - * The mode to start the hotword recognizer in. - * @enum {string} - */ - var RecognizerStartMode = { - NORMAL: 'normal', - NEW_MODEL: 'new model', - ADAPT_MODEL: 'adapt model' - }; - - /** - * MediaStream open success/errors to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaMediaStreamOpenResult = { - SUCCESS: 0, - UNKNOWN: 1, - NOT_SUPPORTED: 2, - PERMISSION_DENIED: 3, - CONSTRAINT_NOT_SATISFIED: 4, - OVERCONSTRAINED: 5, - NOT_FOUND: 6, - ABORT: 7, - SOURCE_UNAVAILABLE: 8, - PERMISSION_DISMISSED: 9, - INVALID_STATE: 10, - DEVICES_NOT_FOUND: 11, - INVALID_SECURITY_ORIGIN: 12, - MAX: 12 - }; - - /** - * UMA metrics. - * DO NOT change these enum values. - * @enum {string} - */ - var UmaMetrics = { - TRIGGER: 'Hotword.HotwordTrigger', - MEDIA_STREAM_RESULT: 'Hotword.HotwordMediaStreamResult', - NACL_PLUGIN_LOAD_RESULT: 'Hotword.HotwordNaClPluginLoadResult', - NACL_MESSAGE_TIMEOUT: 'Hotword.HotwordNaClMessageTimeout', - TRIGGER_SOURCE: 'Hotword.HotwordTriggerSource' - }; - - /** - * Message waited for by NaCl plugin, to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaNaClMessageTimeout = { - REQUEST_MODEL: 0, - MODEL_LOADED: 1, - READY_FOR_AUDIO: 2, - STOPPED: 3, - HOTWORD_DETECTED: 4, - MS_CONFIGURED: 5, - MAX: 5 - }; - - /** - * NaCl plugin load success/errors to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaNaClPluginLoadResult = - {SUCCESS: 0, UNKNOWN: 1, CRASH: 2, NO_MODULE_FOUND: 3, MAX: 3}; - - /** - * Source of hotword triggering, to be reported via UMA. - * DO NOT remove or renumber values in this enum. Only add new ones. - * @enum {number} - */ - var UmaTriggerSource = - {LAUNCHER: 0, NTP_GOOGLE_COM: 1, ALWAYS_ON: 2, TRAINING: 3, MAX: 3}; - - /** - * The browser UI language. - * @const {string} - */ - var UI_LANGUAGE = (chrome.i18n && chrome.i18n.getUILanguage) ? - chrome.i18n.getUILanguage() : - ''; - - return { - AUDIO_LOG_SECONDS: AUDIO_LOG_SECONDS, - CLIENT_PORT_NAME: CLIENT_PORT_NAME, - COMMAND_FIELD_NAME: COMMAND_FIELD_NAME, - FILE_SYSTEM_SIZE_BYTES: FILE_SYSTEM_SIZE_BYTES, - HOTWORD_STREAM_TIMEOUT_SECONDS: HOTWORD_STREAM_TIMEOUT_SECONDS, - NUM_TRAINING_UTTERANCES: NUM_TRAINING_UTTERANCES, - SHARED_MODULE_ID: SHARED_MODULE_ID, - SHARED_MODULE_ROOT: SHARED_MODULE_ROOT, - SPEAKER_MODEL_FILE_NAME: SPEAKER_MODEL_FILE_NAME, - UI_LANGUAGE: UI_LANGUAGE, - UTTERANCE_FILE_EXTENSION: UTTERANCE_FILE_EXTENSION, - UTTERANCE_FILE_PREFIX: UTTERANCE_FILE_PREFIX, - CommandToPage: CommandToPage, - CommandFromPage: CommandFromPage, - Error: Error, - Event: Event, - File: File, - NaClPlugin: NaClPlugin, - RecognizerStartMode: RecognizerStartMode, - SessionSource: SessionSource, - TimeoutMs: TimeoutMs, - UmaMediaStreamOpenResult: UmaMediaStreamOpenResult, - UmaMetrics: UmaMetrics, - UmaNaClMessageTimeout: UmaNaClMessageTimeout, - UmaNaClPluginLoadResult: UmaNaClPluginLoadResult, - UmaTriggerSource: UmaTriggerSource - }; - -}); diff --git a/chrome/browser/resources/hotword/keep_alive.js b/chrome/browser/resources/hotword/keep_alive.js deleted file mode 100644 index 20ff2eabb9db1..0000000000000 --- a/chrome/browser/resources/hotword/keep_alive.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to keep this extension alive. When started, this calls an - * extension API on a regular basis which resets the event page keep-alive - * timer. - * @constructor - */ - function KeepAlive() { - this.timeoutId_ = null; - } - - KeepAlive.prototype = { - /** - * Start the keep alive process. Safe to call multiple times. - */ - start: function() { - if (this.timeoutId_ == null) - this.timeoutId_ = setTimeout(this.handleTimeout_.bind(this), 1000); - }, - - /** - * Stops the keep alive process. Safe to call multiple times. - */ - stop: function() { - if (this.timeoutId_ != null) { - clearTimeout(this.timeoutId_); - this.timeoutId_ = null; - } - }, - - /** - * Handle the timer timeout. Calls an extension API and schedules the next - * timeout. - * @private - */ - handleTimeout_: function() { - // Dummy extensions API call used to keep this event page alive by - // resetting the shutdown timer. - chrome.runtime.getPlatformInfo(function(info) {}); - - this.timeoutId_ = setTimeout(this.handleTimeout_.bind(this), 1000); - } - }; - - return {KeepAlive: KeepAlive}; -}); diff --git a/chrome/browser/resources/hotword/launcher_manager.js b/chrome/browser/resources/hotword/launcher_manager.js deleted file mode 100644 index 144c247eec48d..0000000000000 --- a/chrome/browser/resources/hotword/launcher_manager.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the interaction between hotwording and the launcher - * (app list). - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function LauncherManager(stateManager) { - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.LAUNCHER); - } - - LauncherManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isSometimesOnEnabled(); - }, - - /** @override */ - onSessionStop: function() { - chrome.hotwordPrivate.setHotwordSessionState(false, function() {}); - } - }; - - return {LauncherManager: LauncherManager}; -}); diff --git a/chrome/browser/resources/hotword/logging.js b/chrome/browser/resources/hotword/logging.js deleted file mode 100644 index e0744e07a420d..0000000000000 --- a/chrome/browser/resources/hotword/logging.js +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Wrapper around console.log allowing debug log message to be enabled during - * development. - * @param {...*} varArgs - */ - function debug(varArgs) { - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) - console.log.apply(console, arguments); - } - - return {DEBUG: false, debug: debug}; -}); diff --git a/chrome/browser/resources/hotword/manager.js b/chrome/browser/resources/hotword/manager.js deleted file mode 100644 index f4ac1473c9af7..0000000000000 --- a/chrome/browser/resources/hotword/manager.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -(function() { -'use strict'; - -/** - * @fileoverview This extension provides hotword triggering capabilites to - * Chrome. - * - * This extension contains all the JavaScript for loading and managing the - * hotword detector. The hotword detector and language model data will be - * provided by a shared module loaded from the web store. - * - * IMPORTANT! Whenever adding new events, the extension version number MUST be - * incremented. - */ - -// Hotwording state. -var stateManager = new hotword.StateManager(); -var pageAudioManager = new hotword.PageAudioManager(stateManager); -var alwaysOnManager = new hotword.AlwaysOnManager(stateManager); -var launcherManager = new hotword.LauncherManager(stateManager); -var trainingManager = new hotword.TrainingManager(stateManager); - -// Detect when hotword settings have changed. -chrome.hotwordPrivate.onEnabledChanged.addListener(function() { - stateManager.updateStatus(); -}); - -// Detect a request to delete the speaker model. -chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function() { - hotword.TrainingManager.handleDeleteSpeakerModel(); -}); - -// Detect a request for the speaker model existence. -chrome.hotwordPrivate.onSpeakerModelExists.addListener(function() { - hotword.TrainingManager.handleSpeakerModelExists(); -}); - -// Detect when the shared module containing the NaCL module and language model -// is installed. -chrome.management.onInstalled.addListener(function(info) { - if (info.id == hotword.constants.SHARED_MODULE_ID) { - hotword.debug('Shared module installed, reloading extension.'); - chrome.runtime.reload(); - } -}); -}()); diff --git a/chrome/browser/resources/hotword/manifest.json b/chrome/browser/resources/hotword/manifest.json deleted file mode 100644 index e22ff936ddb34..0000000000000 --- a/chrome/browser/resources/hotword/manifest.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - // Extension ID: nbpagnldghgfoolbancepceaanlmhfmd - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbHXRPiq2De9EJ+4pvNN6uE/D2avxrqyLSpA/Hq3II+btkPl1gboY3oUPTfevpVOFa90Y1c1b3/W682dXqybT0klIvFLKhdQx0LiVqSUQyIaDrwOCSo/ZcukbEwDRojegWymCjHvX6WZk4kKZzTJYzY1vrp0TWKLhttEMN9KFmowIDAQAB", - - "name": "Hotword triggering", - "version": "0.0.1.4", - "manifest_version": 2, - - "background": { - "scripts": [ - "chrome://resources/js/cr.js", - "chrome://resources/js/util.js", - "chrome://resources/js/cr/event_target.js", - "constants.js", - "keep_alive.js", - "logging.js", - "metrics.js", - "nacl_manager.js", - "state_manager.js", - "base_session_manager.js", - "always_on_manager.js", - "launcher_manager.js", - "page_audio_manager.js", - "training_manager.js", - "manager.js" - ], - "persistent": false - }, - - "permissions": [ - "*://*.google.at/*", - "*://*.google.ca/*", - "*://*.google.com/*", - "*://*.google.com.au/*", - "*://*.google.com.mx/*", - "*://*.google.com.br/*", - "*://*.google.co.jp/*", - "*://*.google.co.kr/*", - "*://*.google.co.nz/*", - "*://*.google.co.uk/*", - "*://*.google.co.za/*", - "*://*.google.de/*", - "*://*.google.es/*", - "*://*.google.fr/*", - "*://*.google.it/*", - "*://*.google.ru/*", - "chrome://newtab/", - "chrome://resources/", - "audioCapture", - "hotwordPrivate", - "idle", - "management", - "metricsPrivate", - "tabs", - "unlimitedStorage" - ], - - "externally_connectable": { - "matches": [ - "*://*.google.at/*", - "*://*.google.ca/*", - "*://*.google.com/*", - "*://*.google.com.au/*", - "*://*.google.com.mx/*", - "*://*.google.com.br/*", - "*://*.google.co.jp/*", - "*://*.google.co.kr/*", - "*://*.google.co.nz/*", - "*://*.google.co.uk/*", - "*://*.google.co.za/*", - "*://*.google.de/*", - "*://*.google.es/*", - "*://*.google.fr/*", - "*://*.google.it/*", - "*://*.google.ru/*", - "chrome://newtab/" - ] - }, - - "import": [ - { - "id": "lccekmodgklaepjeofjdjpbminllajkg" - } - ], - - "content_security_policy": "object-src 'none'; script-src chrome://resources 'self' blob: filesystem:", - "minimum_chrome_version": "38" -} diff --git a/chrome/browser/resources/hotword/metrics.js b/chrome/browser/resources/hotword/metrics.js deleted file mode 100644 index 7d4001bf3ec49..0000000000000 --- a/chrome/browser/resources/hotword/metrics.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword.metrics', function() { - 'use strict'; - - /** - * Helper function to record enum values in UMA. - * @param {!string} name - * @param {!number} value - * @param {!number} maxValue - */ - function recordEnum(name, value, maxValue) { - var metricDesc = { - 'metricName': name, - 'type': chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LINEAR, - 'min': 1, - 'max': maxValue, - 'buckets': maxValue + 1 - }; - chrome.metricsPrivate.recordValue(metricDesc, value); - } - - return {recordEnum: recordEnum}; -}); diff --git a/chrome/browser/resources/hotword/nacl_manager.js b/chrome/browser/resources/hotword/nacl_manager.js deleted file mode 100644 index 015399f346c73..0000000000000 --- a/chrome/browser/resources/hotword/nacl_manager.js +++ /dev/null @@ -1,612 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the state of the NaCl recognizer plugin. Handles all - * control of the NaCl plugin, including creation, start, stop, trigger, and - * shutdown. - * - * @param {boolean} loggingEnabled Whether audio logging is enabled. - * @param {boolean} hotwordStream Whether the audio input stream is from a - * hotword stream. - * @constructor - * @extends {cr.EventTarget} - */ - function NaClManager(loggingEnabled, hotwordStream) { - /** - * Current state of this manager. - * @private {hotword.NaClManager.ManagerState_} - */ - this.recognizerState_ = ManagerState_.UNINITIALIZED; - - /** - * The window.timeout ID associated with a pending message. - * @private {?number} - */ - this.naclTimeoutId_ = null; - - /** - * The expected message that will cancel the current timeout. - * @private {?string} - */ - this.expectingMessage_ = null; - - /** - * Whether the plugin will be started as soon as it stops. - * @private {boolean} - */ - this.restartOnStop_ = false; - - /** - * NaCl plugin element on extension background page. - * @private {?HTMLEmbedElement} - */ - this.plugin_ = null; - - /** - * URL containing hotword-model data file. - * @private {string} - */ - this.modelUrl_ = ''; - - /** - * Media stream containing an audio input track. - * @private {?MediaStream} - */ - this.stream_ = null; - - /** - * The mode to start the recognizer in. - * @private {?chrome.hotwordPrivate.RecognizerStartMode} - */ - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - - /** - * Whether audio logging is enabled. - * @private {boolean} - */ - this.loggingEnabled_ = loggingEnabled; - - /** - * Whether the audio input stream is from a hotword stream. - * @private {boolean} - */ - this.hotwordStream_ = hotwordStream; - - /** - * Audio log of X seconds before hotword triggered. - * @private {?Object} - */ - this.preambleLog_ = null; - } - - /** - * States this manager can be in. Since messages to/from the plugin are - * asynchronous (and potentially queued), it's not possible to know what state - * the plugin is in. However, track a state machine for NaClManager based on - * what messages are sent/received. - * @enum {number} - * @private - */ - NaClManager.ManagerState_ = { - UNINITIALIZED: 0, - LOADING: 1, - STOPPING: 2, - STOPPED: 3, - STARTING: 4, - RUNNING: 5, - ERROR: 6, - SHUTDOWN: 7, - }; - var ManagerState_ = NaClManager.ManagerState_; - var Error_ = hotword.constants.Error; - var UmaNaClMessageTimeout_ = hotword.constants.UmaNaClMessageTimeout; - var UmaNaClPluginLoadResult_ = hotword.constants.UmaNaClPluginLoadResult; - - NaClManager.prototype.__proto__ = cr.EventTarget.prototype; - - /** - * Called when an error occurs. Dispatches an event. - * @param {!hotword.constants.Error} error - * @private - */ - NaClManager.prototype.handleError_ = function(error) { - var event = new Event(hotword.constants.Event.ERROR); - event.data = error; - this.dispatchEvent(event); - }; - - /** - * Record the result of loading the NaCl plugin to UMA. - * @param {!hotword.constants.UmaNaClPluginLoadResult} error - * @private - */ - NaClManager.prototype.logPluginLoadResult_ = function(error) { - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.NACL_PLUGIN_LOAD_RESULT, error, - UmaNaClPluginLoadResult_.MAX); - }; - - /** - * Set a timeout. Only allow one timeout to exist at any given time. - * @param {!function()} func - * @param {number} timeout - * @private - */ - NaClManager.prototype.setTimeout_ = function(func, timeout) { - assert(!this.naclTimeoutId_, 'Timeout already exists'); - this.naclTimeoutId_ = window.setTimeout(function() { - this.naclTimeoutId_ = null; - func(); - }.bind(this), timeout); - }; - - /** - * Clears the current timeout. - * @private - */ - NaClManager.prototype.clearTimeout_ = function() { - window.clearTimeout(this.naclTimeoutId_); - this.naclTimeoutId_ = null; - }; - - /** - * Starts a stopped or stopping hotword recognizer (NaCl plugin). - * @param {hotword.constants.RecognizerStartMode} mode The mode to start the - * recognizer in. - */ - NaClManager.prototype.startRecognizer = function(mode) { - this.startMode_ = mode; - if (this.recognizerState_ == ManagerState_.STOPPED) { - this.preambleLog_ = null; - this.recognizerState_ = ManagerState_.STARTING; - if (mode == hotword.constants.RecognizerStartMode.NEW_MODEL) { - hotword.debug('Starting Recognizer in START training mode'); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.BEGIN_SPEAKER_MODEL); - } else if (mode == hotword.constants.RecognizerStartMode.ADAPT_MODEL) { - hotword.debug('Starting Recognizer in ADAPT training mode'); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.ADAPT_SPEAKER_MODEL); - } else { - hotword.debug('Starting Recognizer in NORMAL mode'); - this.sendDataToPlugin_(hotword.constants.NaClPlugin.RESTART); - } - // Normally, there would be a waitForMessage_(READY_FOR_AUDIO) here. - // However, this message is sent the first time audio data is read and in - // some cases (ie. using the hotword stream), this won't happen until a - // potential hotword trigger is seen. Having a waitForMessage_() would - // time - // out in this case, so just leave it out. This ends up sacrificing a bit - // of - // error detection in the non-hotword-stream case, but I think we can live - // with that. - } else if (this.recognizerState_ == ManagerState_.STOPPING) { - // Wait until the plugin is stopped before trying to start it. - this.restartOnStop_ = true; - } else { - throw 'Attempting to start NaCl recogniser not in STOPPED or STOPPING ' + - 'state'; - } - }; - - /** - * Stops the hotword recognizer. - */ - NaClManager.prototype.stopRecognizer = function() { - if (this.recognizerState_ == ManagerState_.STARTING) { - // If the recognizer is stopped before it finishes starting, it causes an - // assertion to be raised in waitForMessage_() since we're waiting for the - // READY_FOR_AUDIO message. Clear the current timeout and expecting - // message - // since we no longer expect it and may never receive it. - this.clearTimeout_(); - this.expectingMessage_ = null; - } - this.sendDataToPlugin_(hotword.constants.NaClPlugin.STOP); - this.recognizerState_ = ManagerState_.STOPPING; - this.waitForMessage_( - hotword.constants.TimeoutMs.NORMAL, - hotword.constants.NaClPlugin.STOPPED); - }; - - /** - * Saves the speaker model. - */ - NaClManager.prototype.finalizeSpeakerModel = function() { - if (this.recognizerState_ == ManagerState_.UNINITIALIZED || - this.recognizerState_ == ManagerState_.ERROR || - this.recognizerState_ == ManagerState_.SHUTDOWN || - this.recognizerState_ == ManagerState_.LOADING) { - return; - } - this.sendDataToPlugin_(hotword.constants.NaClPlugin.FINISH_SPEAKER_MODEL); - }; - - /** - * Checks whether the file at the given path exists. - * @param {!string} path Path to a file. Can be any valid URL. - * @return {boolean} True if the patch exists. - * @private - */ - NaClManager.prototype.fileExists_ = function(path) { - var xhr = new XMLHttpRequest(); - xhr.open('HEAD', path, false); - try { - xhr.send(); - } catch (err) { - return false; - } - if (xhr.readyState != xhr.DONE || xhr.status != 200) { - return false; - } - return true; - }; - - /** - * Creates and returns a list of possible languages to check for hotword - * support. - * @return {!Array} Array of languages. - * @private - */ - NaClManager.prototype.getPossibleLanguages_ = function() { - // Create array used to search first for language-country, if not found then - // search for language, if not found then no language (empty string). - // For example, search for 'en-us', then 'en', then ''. - var langs = new Array(); - if (hotword.constants.UI_LANGUAGE) { - // Chrome webstore doesn't support uppercase path: crbug.com/353407 - var language = hotword.constants.UI_LANGUAGE.toLowerCase(); - langs.push(language); // Example: 'en-us'. - // Remove country to add just the language to array. - var hyphen = language.lastIndexOf('-'); - if (hyphen >= 0) { - langs.push(language.substr(0, hyphen)); // Example: 'en'. - } - } - langs.push(''); - return langs; - }; - - /** - * Creates a NaCl plugin object and attaches it to the page. - * @param {!string} src Location of the plugin. - * @return {!HTMLEmbedElement} NaCl plugin DOM object. - * @private - */ - NaClManager.prototype.createPlugin_ = function(src) { - var plugin = - /** @type {HTMLEmbedElement} */ (document.createElement('embed')); - plugin.src = src; - plugin.type = 'application/x-nacl'; - document.body.appendChild(plugin); - return plugin; - }; - - /** - * Initializes the NaCl manager. - * @param {!string} naclArch Either 'arm', 'x86-32' or 'x86-64'. - * @param {!MediaStream} stream A stream containing an audio source track. - * @return {boolean} True if the successful. - */ - NaClManager.prototype.initialize = function(naclArch, stream) { - assert( - this.recognizerState_ == ManagerState_.UNINITIALIZED, - 'Recognizer not in uninitialized state. State: ' + - this.recognizerState_); - assert(this.plugin_ == null); - var langs = this.getPossibleLanguages_(); - var i, j; - // For country-lang variations. For example, when combined with path it will - // attempt to find: '/x86-32_en-gb/', else '/x86-32_en/', else '/x86-32_/'. - for (i = 0; i < langs.length; i++) { - var folder = hotword.constants.SHARED_MODULE_ROOT + - '/_platform_specific/' + naclArch + '_' + langs[i] + '/'; - var dataSrc = folder + hotword.constants.File.RECOGNIZER_CONFIG; - var pluginSrc = hotword.constants.SHARED_MODULE_ROOT + '/hotword_' + - langs[i] + '.nmf'; - var dataExists = this.fileExists_(dataSrc) && this.fileExists_(pluginSrc); - if (!dataExists) { - continue; - } - - var plugin = this.createPlugin_(pluginSrc); - if (!plugin || !plugin.postMessage) { - document.body.removeChild(plugin); - this.recognizerState_ = ManagerState_.ERROR; - return false; - } - this.plugin_ = plugin; - this.modelUrl_ = chrome.extension.getURL(dataSrc); - this.stream_ = stream; - this.recognizerState_ = ManagerState_.LOADING; - - plugin.addEventListener( - 'message', this.handlePluginMessage_.bind(this), false); - - plugin.addEventListener('crash', function() { - this.handleError_(Error_.NACL_CRASH); - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.CRASH); - }.bind(this), false); - return true; - } - this.recognizerState_ = ManagerState_.ERROR; - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.NO_MODULE_FOUND); - return false; - }; - - /** - * Shuts down the NaCl plugin and frees all resources. - */ - NaClManager.prototype.shutdown = function() { - if (this.plugin_ != null) { - document.body.removeChild(this.plugin_); - this.plugin_ = null; - } - this.clearTimeout_(); - this.recognizerState_ = ManagerState_.SHUTDOWN; - if (this.stream_) - this.stream_.getAudioTracks()[0].stop(); - this.stream_ = null; - }; - - /** - * Sends data to the NaCl plugin. - * @param {!string|!MediaStreamTrack} data Command to be sent to NaCl plugin. - * @private - */ - NaClManager.prototype.sendDataToPlugin_ = function(data) { - assert( - this.recognizerState_ != ManagerState_.UNINITIALIZED, - 'Recognizer in uninitialized state'); - this.plugin_.postMessage(data); - }; - - /** - * Waits, with a timeout, for a message to be received from the plugin. If the - * message is not seen within the timeout, dispatch an 'error' event and go - * into - * the ERROR state. - * @param {number} timeout Timeout, in milliseconds, to wait for the message. - * @param {!string} message Message to wait for. - * @private - */ - NaClManager.prototype.waitForMessage_ = function(timeout, message) { - assert( - this.expectingMessage_ == null, - 'Cannot wait for message: ' + message + - ', already waiting for message ' + this.expectingMessage_); - this.setTimeout_(function() { - this.recognizerState_ = ManagerState_.ERROR; - this.handleError_(Error_.TIMEOUT); - switch (this.expectingMessage_) { - case hotword.constants.NaClPlugin.REQUEST_MODEL: - var metricValue = UmaNaClMessageTimeout_.REQUEST_MODEL; - break; - case hotword.constants.NaClPlugin.MODEL_LOADED: - var metricValue = UmaNaClMessageTimeout_.MODEL_LOADED; - break; - case hotword.constants.NaClPlugin.READY_FOR_AUDIO: - var metricValue = UmaNaClMessageTimeout_.READY_FOR_AUDIO; - break; - case hotword.constants.NaClPlugin.STOPPED: - var metricValue = UmaNaClMessageTimeout_.STOPPED; - break; - case hotword.constants.NaClPlugin.HOTWORD_DETECTED: - var metricValue = UmaNaClMessageTimeout_.HOTWORD_DETECTED; - break; - case hotword.constants.NaClPlugin.MS_CONFIGURED: - var metricValue = UmaNaClMessageTimeout_.MS_CONFIGURED; - break; - } - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.NACL_MESSAGE_TIMEOUT, metricValue, - UmaNaClMessageTimeout_.MAX); - }.bind(this), timeout); - this.expectingMessage_ = message; - }; - - /** - * Called when a message is received from the plugin. If we're waiting for - * that - * message, cancel the pending timeout. - * @param {string} message Message received. - * @private - */ - NaClManager.prototype.receivedMessage_ = function(message) { - if (message == this.expectingMessage_) { - this.clearTimeout_(); - this.expectingMessage_ = null; - } - }; - - /** - * Handle a REQUEST_MODEL message from the plugin. - * The plugin sends this message immediately after starting. - * @private - */ - NaClManager.prototype.handleRequestModel_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.logPluginLoadResult_(UmaNaClPluginLoadResult_.SUCCESS); - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.MODEL_PREFIX + this.modelUrl_); - this.waitForMessage_( - hotword.constants.TimeoutMs.LONG, - hotword.constants.NaClPlugin.MODEL_LOADED); - - // Configure logging in the plugin. This can be configured any time before - // starting the recognizer, and now is as good a time as any. - if (this.loggingEnabled_) { - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.LOG + ':' + - hotword.constants.AUDIO_LOG_SECONDS); - } - - // If the audio stream is from a hotword stream, tell the plugin. - if (this.hotwordStream_) { - this.sendDataToPlugin_( - hotword.constants.NaClPlugin.DSP + ':' + - hotword.constants.HOTWORD_STREAM_TIMEOUT_SECONDS); - } - }; - - /** - * Handle a MODEL_LOADED message from the plugin. - * The plugin sends this message after successfully loading the language - * model. - * @private - */ - NaClManager.prototype.handleModelLoaded_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.sendDataToPlugin_(this.stream_.getAudioTracks()[0]); - // The plugin will send a MS_CONFIGURED, but don't set a timeout waiting for - // it. MediaStreamAudioTrack::Configure() will remain pending until the - // first - // audio buffer is received. When the audio source is a DSP for always-on - // detection, no audio sample is sent until the DSP detects a potential - // hotword trigger. Thus, Configure would remain pending indefinitely if we - // were to wait here. See https://crbug.com/616203 - }; - - /** - * Handle a MS_CONFIGURED message from the plugin. - * The plugin sends this message after successfully configuring the audio - * input - * stream. - * @private - */ - NaClManager.prototype.handleMsConfigured_ = function() { - if (this.recognizerState_ != ManagerState_.LOADING) { - return; - } - this.recognizerState_ = ManagerState_.STOPPED; - this.dispatchEvent(new Event(hotword.constants.Event.READY)); - }; - - /** - * Handle a READY_FOR_AUDIO message from the plugin. - * The plugin sends this message after the recognizer is started and - * successfully receives and processes audio data. - * @private - */ - NaClManager.prototype.handleReadyForAudio_ = function() { - if (this.recognizerState_ != ManagerState_.STARTING) { - return; - } - this.recognizerState_ = ManagerState_.RUNNING; - }; - - /** - * Handle a HOTWORD_DETECTED message from the plugin. - * The plugin sends this message after detecting the hotword. - * @private - */ - NaClManager.prototype.handleHotwordDetected_ = function() { - if (this.recognizerState_ != ManagerState_.RUNNING) { - return; - } - // We'll receive a STOPPED message very soon. - this.recognizerState_ = ManagerState_.STOPPING; - this.waitForMessage_( - hotword.constants.TimeoutMs.NORMAL, - hotword.constants.NaClPlugin.STOPPED); - var event = new Event(hotword.constants.Event.TRIGGER); - event.log = this.preambleLog_; - this.dispatchEvent(event); - }; - - /** - * Handle a STOPPED message from the plugin. - * This plugin sends this message after stopping the recognizer. This can - * happen - * either in response to a stop request, or after the hotword is detected. - * @private - */ - NaClManager.prototype.handleStopped_ = function() { - this.recognizerState_ = ManagerState_.STOPPED; - if (this.restartOnStop_) { - this.restartOnStop_ = false; - this.startRecognizer(this.startMode_); - } - }; - - /** - * Handle a TIMEOUT message from the plugin. - * The plugin sends this message when it thinks the stream is from a DSP and - * a hotword wasn't detected within a timeout period after arrival of the - * first - * audio samples. - * @private - */ - NaClManager.prototype.handleTimeout_ = function() { - if (this.recognizerState_ != ManagerState_.RUNNING) { - return; - } - this.recognizerState_ = ManagerState_.STOPPED; - this.dispatchEvent(new Event(hotword.constants.Event.TIMEOUT)); - }; - - /** - * Handle a SPEAKER_MODEL_SAVED message from the plugin. - * The plugin sends this message after writing the model to a file. - * @private - */ - NaClManager.prototype.handleSpeakerModelSaved_ = function() { - this.dispatchEvent(new Event(hotword.constants.Event.SPEAKER_MODEL_SAVED)); - }; - - /** - * Handles a message from the NaCl plugin. - * @param {!Event} msg Message from NaCl plugin. - * @private - */ - NaClManager.prototype.handlePluginMessage_ = function(msg) { - if (msg['data']) { - if (typeof(msg['data']) == 'object') { - // Save the preamble for delivery to the trigger handler when the - // trigger - // message arrives. - this.preambleLog_ = msg['data']; - return; - } - this.receivedMessage_(msg['data']); - switch (msg['data']) { - case hotword.constants.NaClPlugin.REQUEST_MODEL: - this.handleRequestModel_(); - break; - case hotword.constants.NaClPlugin.MODEL_LOADED: - this.handleModelLoaded_(); - break; - case hotword.constants.NaClPlugin.MS_CONFIGURED: - this.handleMsConfigured_(); - break; - case hotword.constants.NaClPlugin.READY_FOR_AUDIO: - this.handleReadyForAudio_(); - break; - case hotword.constants.NaClPlugin.HOTWORD_DETECTED: - this.handleHotwordDetected_(); - break; - case hotword.constants.NaClPlugin.STOPPED: - this.handleStopped_(); - break; - case hotword.constants.NaClPlugin.TIMEOUT: - this.handleTimeout_(); - break; - case hotword.constants.NaClPlugin.SPEAKER_MODEL_SAVED: - this.handleSpeakerModelSaved_(); - break; - } - } - }; - - return {NaClManager: NaClManager}; - -}); diff --git a/chrome/browser/resources/hotword/page_audio_manager.js b/chrome/browser/resources/hotword/page_audio_manager.js deleted file mode 100644 index 8c8c928cf084b..0000000000000 --- a/chrome/browser/resources/hotword/page_audio_manager.js +++ /dev/null @@ -1,541 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage the interaction between hotwording and the - * NTP/google.com. Injects a content script to interact with NTP/google.com - * and updates the global hotwording state based on interaction with those - * pages. - * @param {!hotword.StateManager} stateManager - * @constructor - */ - function PageAudioManager(stateManager) { - /** - * Manager of global hotwording state. - * @private {!hotword.StateManager} - */ - this.stateManager_ = stateManager; - - /** - * Mapping between tab ID and port that is connected from the injected - * content script. - * @private {!Object} - */ - this.portMap_ = {}; - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - */ - this.connectListener_ = this.handleConnect_.bind(this); - this.tabCreatedListener_ = this.handleCreatedTab_.bind(this); - this.tabUpdatedListener_ = this.handleUpdatedTab_.bind(this); - this.tabActivatedListener_ = this.handleActivatedTab_.bind(this); - this.microphoneStateChangedListener_ = - this.handleMicrophoneStateChanged_.bind(this); - this.windowFocusChangedListener_ = this.handleChangedWindow_.bind(this); - this.messageListener_ = this.handleMessageFromPage_.bind(this); - - // Need to setup listeners on startup, otherwise events that caused the - // event page to start up, will be lost. - this.setupListeners_(); - - this.stateManager_.onStatusChanged.addListener(function() { - this.updateListeners_(); - this.updateTabState_(); - }.bind(this)); - } - - var CommandToPage = hotword.constants.CommandToPage; - var CommandFromPage = hotword.constants.CommandFromPage; - - PageAudioManager.prototype = { - /** - * Helper function to test if a URL path is eligible for hotwording. - * @param {!string} url URL to check. - * @param {!string} base Base URL to compare against.. - * @return {boolean} True if url is an eligible hotword URL. - * @private - */ - checkUrlPathIsEligible_: function(url, base) { - if (url == base || url == base + '/' || - url.startsWith(base + '/_/chrome/newtab?') || // Appcache NTP. - url.startsWith(base + '/?') || url.startsWith(base + '/#') || - url.startsWith(base + '/webhp') || url.startsWith(base + '/search') || - url.startsWith(base + '/imghp')) { - return true; - } - return false; - }, - - /** - * Determines if a URL is eligible for hotwording. For now, the valid pages - * are the Google HP and SERP (this will include the NTP). - * @param {!string} url URL to check. - * @return {boolean} True if url is an eligible hotword URL. - * @private - */ - isEligibleUrl_: function(url) { - if (!url) - return false; - - var baseGoogleUrls = [ - 'https://encrypted.google.', 'https://images.google.', - 'https://www.google.' - ]; - // TODO(amistry): Get this list from a file in the shared module instead. - var tlds = [ - 'at', 'ca', 'com', 'com.au', 'com.mx', 'com.br', 'co.jp', 'co.kr', - 'co.nz', 'co.uk', 'co.za', 'de', 'es', 'fr', 'it', 'ru' - ]; - - // Check for the new tab page first. - if (this.checkUrlPathIsEligible_(url, 'chrome://newtab')) - return true; - - // Check URLs with each type of local-based TLD. - for (var i = 0; i < baseGoogleUrls.length; i++) { - for (var j = 0; j < tlds.length; j++) { - var base = baseGoogleUrls[i] + tlds[j]; - if (this.checkUrlPathIsEligible_(url, base)) - return true; - } - } - return false; - }, - - /** - * Locates the current active tab in the current focused window and - * performs a callback with the tab as the parameter. - * @param {function(?Tab)} callback Function to call with the - * active tab or null if not found. The function's |this| will be set to - * this object. - * @private - */ - findCurrentTab_: function(callback) { - chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; ++i) { - if (!windows[i].focused) - continue; - - for (var j = 0; j < windows[i].tabs.length; ++j) { - var tab = windows[i].tabs[j]; - if (tab.active) { - callback.call(this, tab); - return; - } - } - } - callback.call(this, null); - }.bind(this)); - }, - - /** - * This function is called when a tab is activated (comes into focus). - * @param {Tab} tab Current active tab. - * @private - */ - activateTab_: function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (tab.id in this.portMap_) { - this.startHotwordingIfEligible_(); - return; - } - this.stopHotwording_(); - this.prepareTab_(tab); - }, - - /** - * Prepare a new or updated tab by injecting the content script. - * @param {!Tab} tab Newly updated or created tab. - * @private - */ - prepareTab_: function(tab) { - if (!this.isEligibleUrl_(tab.url)) - return; - - chrome.tabs.executeScript( - tab.id, {'file': 'audio_client.js'}, function(results) { - if (chrome.runtime.lastError) { - // Ignore this error. For new tab pages, even though the URL is - // reported to be chrome://newtab/, the actual URL is a - // country-specific google domain. Since we don't have permission - // to inject on every page, an error will happen when the user is - // in an unsupported country. - // - // The property still needs to be accessed so that the error - // condition is cleared. If it isn't, exectureScript will log an - // error the next time it is called. - } - }); - }, - - /** - * Updates hotwording state based on the state of current tabs/windows. - * @private - */ - updateTabState_: function() { - this.findCurrentTab_(this.activateTab_); - }, - - /** - * Handles a newly created tab. - * @param {!Tab} tab Newly created tab. - * @private - */ - handleCreatedTab_: function(tab) { - this.prepareTab_(tab); - }, - - /** - * Handles an updated tab. - * @param {number} tabId Id of the updated tab. - * @param {{status: string}} info Change info of the tab. - * @param {!Tab} tab Updated tab. - * @private - */ - handleUpdatedTab_: function(tabId, info, tab) { - // Chrome fires multiple update events: undefined, loading and completed. - // We perform content injection on loading state. - if (info['status'] != 'loading') - return; - - this.prepareTab_(tab); - }, - - /** - * Handles a tab that has just become active. - * @param {{tabId: number}} info Information about the activated tab. - * @private - */ - handleActivatedTab_: function(info) { - this.updateTabState_(); - }, - - /** - * Handles the microphone state changing. - * @param {boolean} enabled Whether the microphone is now enabled. - * @private - */ - handleMicrophoneStateChanged_: function(enabled) { - if (enabled) { - this.updateTabState_(); - return; - } - - this.stopHotwording_(); - }, - - /** - * Handles a change in Chrome windows. - * Note: this does not always trigger in Linux. - * @param {number} windowId Id of newly focused window. - * @private - */ - handleChangedWindow_: function(windowId) { - this.updateTabState_(); - }, - - /** - * Handles a content script attempting to connect. - * @param {!Port} port Communications port from the client. - * @private - */ - handleConnect_: function(port) { - if (port.name != hotword.constants.CLIENT_PORT_NAME) - return; - - var tab = /** @type {!Tab} */ (port.sender.tab); - // An existing port from the same tab might already exist. But that port - // may be from the previous page, so just overwrite the port. - this.portMap_[tab.id] = port; - port.onDisconnect.addListener(function() { - this.handleClientDisconnect_(port); - }.bind(this)); - port.onMessage.addListener(function(msg) { - this.handleMessage_(msg, port.sender, port.postMessage); - }.bind(this)); - }, - - /** - * Handles a client content script disconnect. - * @param {Port} port Disconnected port. - * @private - */ - handleClientDisconnect_: function(port) { - var tabId = port.sender.tab.id; - if (tabId in this.portMap_ && this.portMap_[tabId] == port) { - // Due to a race between port disconnection and tabs.onUpdated messages, - // the port could have changed. - delete this.portMap_[port.sender.tab.id]; - } - this.stopHotwordingIfIneligibleTab_(); - }, - - /** - * Disconnect all connected clients. - * @private - */ - disconnectAllClients_: function() { - for (var id in this.portMap_) { - var port = this.portMap_[id]; - port.disconnect(); - delete this.portMap_[id]; - } - }, - - /** - * Sends a command to the client content script on an eligible tab. - * @param {hotword.constants.CommandToPage} command Command to send. - * @param {number} tabId Id of the target tab. - * @private - */ - sendClient_: function(command, tabId) { - if (tabId in this.portMap_) { - var message = {}; - message[hotword.constants.COMMAND_FIELD_NAME] = command; - this.portMap_[tabId].postMessage(message); - } - }, - - /** - * Sends a command to all connected clients. - * @param {hotword.constants.CommandToPage} command Command to send. - * @private - */ - sendAllClients_: function(command) { - for (var idStr in this.portMap_) { - var id = parseInt(idStr, 10); - assert(!isNaN(id), 'Tab ID is not a number: ' + idStr); - this.sendClient_(command, id); - } - }, - - /** - * Handles a hotword trigger. Sends a trigger message to the currently - * active tab. - * @private - */ - hotwordTriggered_: function() { - this.findCurrentTab_(function(tab) { - if (tab) - this.sendClient_(CommandToPage.HOTWORD_VOICE_TRIGGER, tab.id); - }); - }, - - /** - * Starts hotwording. - * @private - */ - startHotwording_: function() { - this.stateManager_.startSession( - hotword.constants.SessionSource.NTP, function() { - this.sendAllClients_(CommandToPage.HOTWORD_STARTED); - }.bind(this), this.hotwordTriggered_.bind(this)); - }, - - /** - * Starts hotwording if the currently active tab is eligible for hotwording - * (e.g. google.com). - * @private - */ - startHotwordingIfEligible_: function() { - this.findCurrentTab_(function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (this.isEligibleUrl_(tab.url)) - this.startHotwording_(); - }); - }, - - /** - * Stops hotwording. - * @private - */ - stopHotwording_: function() { - this.stateManager_.stopSession(hotword.constants.SessionSource.NTP); - this.sendAllClients_(CommandToPage.HOTWORD_ENDED); - }, - - /** - * Stops hotwording if the currently active tab is not eligible for - * hotwording (i.e. google.com). - * @private - */ - stopHotwordingIfIneligibleTab_: function() { - this.findCurrentTab_(function(tab) { - if (!tab) { - this.stopHotwording_(); - return; - } - if (!this.isEligibleUrl_(tab.url)) - this.stopHotwording_(); - }); - }, - - /** - * Handles a message from the content script injected into the page. - * @param {!Object} request Request from the content script. - * @param {!MessageSender} sender Message sender. - * @param {!function(Object)} sendResponse Function for sending a response. - * @private - */ - handleMessage_: function(request, sender, sendResponse) { - switch (request[hotword.constants.COMMAND_FIELD_NAME]) { - // TODO(amistry): Handle other messages such as CLICKED_RESUME and - // CLICKED_RESTART, if necessary. - case CommandFromPage.SPEECH_START: - this.stopHotwording_(); - break; - case CommandFromPage.SPEECH_END: - case CommandFromPage.SPEECH_RESET: - this.startHotwording_(); - break; - } - }, - - - /** - * Handles a message directly from the NTP/HP/SERP. - * @param {!Object} request Message from the sender. - * @param {!MessageSender} sender Information about the sender. - * @param {!function(HotwordStatus)} sendResponse Callback to respond - * to sender. - * @return {boolean} Whether to maintain the port open to call sendResponse. - * @private - */ - handleMessageFromPage_: function(request, sender, sendResponse) { - switch (request.type) { - case CommandFromPage.PAGE_WAKEUP: - if (sender.tab && this.isEligibleUrl_(sender.tab.url)) { - chrome.hotwordPrivate.getStatus( - true /* getOptionalFields */, - this.statusDone_.bind( - this, request.tab || sender.tab || {incognito: true}, - sendResponse)); - return true; - } - - // Do not show the opt-in promo for ineligible urls. - this.sendResponse_({'doNotShowOptinMessage': true}, sendResponse); - break; - case CommandFromPage.CLICKED_OPTIN: - chrome.hotwordPrivate.setEnabled(true); - break; - // User has explicitly clicked 'no thanks'. - case CommandFromPage.CLICKED_NO_OPTIN: - chrome.hotwordPrivate.setEnabled(false); - break; - } - return false; - }, - - /** - * Sends a message directly to the sending page. - * @param {!HotwordStatus} response The response to send to the sender. - * @param {!function(HotwordStatus)} sendResponse Callback to respond - * to sender. - * @private - */ - sendResponse_: function(response, sendResponse) { - try { - sendResponse(response); - } catch (err) { - // Suppress the exception thrown by sendResponse() when the page doesn't - // specify a response callback in the call to - // chrome.runtime.sendMessage(). - // Unfortunately, there doesn't appear to be a way to detect one-way - // messages without explicitly saying in the message itself. This - // message is defined as a constant in - // extensions/renderer/messaging_bindings.cc - if (err.message == 'Attempting to use a disconnected port object') - return; - throw err; - } - }, - - /** - * Sends the response to the tab. - * @param {Tab} tab The tab that the request was sent from. - * @param {function(HotwordStatus)} sendResponse Callback function to - * respond to sender. - * @param {HotwordStatus} hotwordStatus Status of the hotword extension. - * @private - */ - statusDone_: function(tab, sendResponse, hotwordStatus) { - var response = {'doNotShowOptinMessage': true}; - - // If always-on is available, then we do not show the promo, as the promo - // only works with the sometimes-on pref. - if (!tab.incognito && hotwordStatus.available && - !hotwordStatus.enabledSet && !hotwordStatus.alwaysOnAvailable) { - response = hotwordStatus; - } - - this.sendResponse_(response, sendResponse); - }, - - /** - * Set up event listeners. - * @private - */ - setupListeners_: function() { - if (chrome.runtime.onConnect.hasListener(this.connectListener_)) - return; - - chrome.runtime.onConnect.addListener(this.connectListener_); - chrome.tabs.onCreated.addListener(this.tabCreatedListener_); - chrome.tabs.onUpdated.addListener(this.tabUpdatedListener_); - chrome.tabs.onActivated.addListener(this.tabActivatedListener_); - chrome.windows.onFocusChanged.addListener( - this.windowFocusChangedListener_); - chrome.hotwordPrivate.onMicrophoneStateChanged.addListener( - this.microphoneStateChangedListener_); - if (chrome.runtime.onMessage.hasListener(this.messageListener_)) - return; - chrome.runtime.onMessageExternal.addListener(this.messageListener_); - }, - - /** - * Remove event listeners. - * @private - */ - removeListeners_: function() { - chrome.runtime.onConnect.removeListener(this.connectListener_); - chrome.tabs.onCreated.removeListener(this.tabCreatedListener_); - chrome.tabs.onUpdated.removeListener(this.tabUpdatedListener_); - chrome.tabs.onActivated.removeListener(this.tabActivatedListener_); - chrome.windows.onFocusChanged.removeListener( - this.windowFocusChangedListener_); - chrome.hotwordPrivate.onMicrophoneStateChanged.removeListener( - this.microphoneStateChangedListener_); - // Don't remove the Message listener, as we want them listening all - // the time, - }, - - /** - * Update event listeners based on the current hotwording state. - * @private - */ - updateListeners_: function() { - if (this.stateManager_.isSometimesOnEnabled()) { - this.setupListeners_(); - } else { - this.removeListeners_(); - this.stopHotwording_(); - this.disconnectAllClients_(); - } - } - }; - - return {PageAudioManager: PageAudioManager}; -}); diff --git a/chrome/browser/resources/hotword/state_manager.js b/chrome/browser/resources/hotword/state_manager.js deleted file mode 100644 index 98e0a5cbd1740..0000000000000 --- a/chrome/browser/resources/hotword/state_manager.js +++ /dev/null @@ -1,641 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Trivial container class for session information. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session. - * @param {!function()} triggerCb Callback invoked when the hotword has - * triggered. - * @param {!function()} startedCb Callback invoked when the session has - * been started successfully. - * @param {function()=} opt_modelSavedCb Callback invoked when the speaker - * model has been saved successfully. - * @constructor - * @struct - * @private - */ - function Session_(source, triggerCb, startedCb, opt_modelSavedCb) { - /** - * Source of the hotword session request. - * @private {!hotword.constants.SessionSource} - */ - this.source_ = source; - - /** - * Callback invoked when the hotword has triggered. - * @private {!function()} - */ - this.triggerCb_ = triggerCb; - - /** - * Callback invoked when the session has been started successfully. - * @private {?function()} - */ - this.startedCb_ = startedCb; - - /** - * Callback invoked when the session has been started successfully. - * @private {?function()} - */ - this.speakerModelSavedCb_ = opt_modelSavedCb; - } - - /** - * Class to manage hotwording state. Starts/stops the hotword detector based - * on user settings, session requests, and any other factors that play into - * whether or not hotwording should be running. - * @constructor - */ - function StateManager() { - /** - * Current state. - * @private {hotword.StateManager.State_} - */ - this.state_ = State_.STOPPED; - - /** - * Current hotwording status. - * @private {?chrome.hotwordPrivate.StatusDetails} - */ - this.hotwordStatus_ = null; - - /** - * NaCl plugin manager. - * @private {?hotword.NaClManager} - */ - this.pluginManager_ = null; - - /** - * Currently active hotwording sessions. - * @private {!Array} - */ - this.sessions_ = []; - - /** - * The mode to start the recognizer in. - * @private {!hotword.constants.RecognizerStartMode} - */ - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - - /** - * Event that fires when the hotwording status has changed. - * @type {!ChromeEvent} - */ - this.onStatusChanged = new chrome.Event(); - - /** - * Hotword trigger audio notification... a.k.a The Chime (tm). - * @private {!HTMLAudioElement} - */ - this.chime_ = - /** @type {!HTMLAudioElement} */ (document.createElement('audio')); - - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.idleStateChangedListener_ = this.handleIdleStateChanged_.bind(this); - this.startupListener_ = this.handleStartup_.bind(this); - - /** - * Whether this user is locked. - * @private {boolean} - */ - this.isLocked_ = false; - - /** - * Current state of audio logging. - * This is tracked separately from hotwordStatus_ because we need to restart - * the hotword detector when this value changes. - * @private {boolean} - */ - this.loggingEnabled_ = false; - - /** - * Current state of training. - * This is tracked separately from |hotwordStatus_| because we need to - * restart the hotword detector when this value changes. - * @private {!boolean} - */ - this.trainingEnabled_ = false; - - /** - * Helper class to keep this extension alive while the hotword detector is - * running in always-on mode. - * @private {!hotword.KeepAlive} - */ - this.keepAlive_ = new hotword.KeepAlive(); - - // Get the initial status. - chrome.hotwordPrivate.getStatus(this.handleStatus_.bind(this)); - - // Setup the chime and insert into the page. - // Set preload=none to prevent an audio output stream from being created - // when the extension loads. - this.chime_.preload = 'none'; - this.chime_.src = chrome.extension.getURL( - hotword.constants.SHARED_MODULE_ROOT + '/audio/chime.wav'); - document.body.appendChild(this.chime_); - - // In order to remove this listener, it must first be added. This handles - // the case on first Chrome startup where this event is never registered, - // so can't be removed when it's determined that hotwording is disabled. - // Why not only remove the listener if it exists? Extension API events have - // two parts to them, the Javascript listeners, and a browser-side component - // that wakes up the extension if it's an event page. The browser-side - // wake-up event is only removed when the number of javascript listeners - // becomes 0. To clear the browser wake-up event, a listener first needs to - // be added, then removed in order to drop the count to 0 and remove the - // event. - chrome.runtime.onStartup.addListener(this.startupListener_); - } - - /** - * @enum {number} - * @private - */ - StateManager.State_ = { - STOPPED: 0, - STARTING: 1, - RUNNING: 2, - ERROR: 3, - }; - var State_ = StateManager.State_; - - var UmaMediaStreamOpenResults_ = { - // These first error are defined by the MediaStream spec: - // http://w3c.github.io/mediacapture-main/getusermedia.html#idl-def-MediaStreamError - 'NotSupportedError': - hotword.constants.UmaMediaStreamOpenResult.NOT_SUPPORTED, - 'PermissionDeniedError': - hotword.constants.UmaMediaStreamOpenResult.PERMISSION_DENIED, - 'ConstraintNotSatisfiedError': - hotword.constants.UmaMediaStreamOpenResult.CONSTRAINT_NOT_SATISFIED, - 'OverconstrainedError': - hotword.constants.UmaMediaStreamOpenResult.OVERCONSTRAINED, - 'NotFoundError': hotword.constants.UmaMediaStreamOpenResult.NOT_FOUND, - 'AbortError': hotword.constants.UmaMediaStreamOpenResult.ABORT, - 'SourceUnavailableError': - hotword.constants.UmaMediaStreamOpenResult.SOURCE_UNAVAILABLE, - // The next few errors are chrome-specific. See: - // content/renderer/media/user_media_client_impl.cc - // (UserMediaClientImpl::GetUserMediaRequestFailed) - 'PermissionDismissedError': - hotword.constants.UmaMediaStreamOpenResult.PERMISSION_DISMISSED, - 'InvalidStateError': - hotword.constants.UmaMediaStreamOpenResult.INVALID_STATE, - 'DevicesNotFoundError': - hotword.constants.UmaMediaStreamOpenResult.DEVICES_NOT_FOUND, - 'InvalidSecurityOriginError': - hotword.constants.UmaMediaStreamOpenResult.INVALID_SECURITY_ORIGIN - }; - - var UmaTriggerSources_ = { - 'launcher': hotword.constants.UmaTriggerSource.LAUNCHER, - 'ntp': hotword.constants.UmaTriggerSource.NTP_GOOGLE_COM, - 'always': hotword.constants.UmaTriggerSource.ALWAYS_ON, - 'training': hotword.constants.UmaTriggerSource.TRAINING - }; - - StateManager.prototype = { - /** - * Request status details update. Intended to be called from the - * hotwordPrivate.onEnabledChanged() event. - */ - updateStatus: function() { - chrome.hotwordPrivate.getStatus(this.handleStatus_.bind(this)); - }, - - /** - * @return {boolean} True if google.com/NTP/launcher hotwording is enabled. - */ - isSometimesOnEnabled: function() { - assert( - this.hotwordStatus_, 'No hotwording status (isSometimesOnEnabled)'); - // Although the two settings are supposed to be mutually exclusive, it's - // possible for both to be set. In that case, always-on takes precedence. - return this.hotwordStatus_.enabled && - !this.hotwordStatus_.alwaysOnEnabled; - }, - - /** - * @return {boolean} True if always-on hotwording is enabled. - */ - isAlwaysOnEnabled: function() { - assert(this.hotwordStatus_, 'No hotword status (isAlwaysOnEnabled)'); - return this.hotwordStatus_.alwaysOnEnabled && - !this.hotwordStatus_.trainingEnabled; - }, - - /** - * @return {boolean} True if training is enabled. - */ - isTrainingEnabled: function() { - assert(this.hotwordStatus_, 'No hotword status (isTrainingEnabled)'); - return this.hotwordStatus_.trainingEnabled; - }, - - /** - * Callback for hotwordPrivate.getStatus() function. - * @param {chrome.hotwordPrivate.StatusDetails} status Current hotword - * status. - * @private - */ - handleStatus_: function(status) { - hotword.debug('New hotword status', status); - this.hotwordStatus_ = status; - this.updateStateFromStatus_(); - - this.onStatusChanged.dispatch(); - }, - - /** - * Updates state based on the current status. - * @private - */ - updateStateFromStatus_: function() { - if (!this.hotwordStatus_) - return; - - if (this.hotwordStatus_.enabled || this.hotwordStatus_.alwaysOnEnabled || - this.hotwordStatus_.trainingEnabled) { - // Detect changes to audio logging and kill the detector if that setting - // has changed. - if (this.hotwordStatus_.audioLoggingEnabled != this.loggingEnabled_) - this.shutdownDetector_(); - this.loggingEnabled_ = this.hotwordStatus_.audioLoggingEnabled; - - // If the training state has changed, we need to first shut down the - // detector so that we can restart in a different mode. - if (this.hotwordStatus_.trainingEnabled != this.trainingEnabled_) - this.shutdownDetector_(); - this.trainingEnabled_ = this.hotwordStatus_.trainingEnabled; - - // Start the detector if there's a session and the user is unlocked, and - // stops it otherwise. - if (this.sessions_.length && !this.isLocked_ && - this.hotwordStatus_.userIsActive) { - this.startDetector_(); - } else { - this.shutdownDetector_(); - } - - if (!chrome.idle.onStateChanged.hasListener( - this.idleStateChangedListener_)) { - chrome.idle.onStateChanged.addListener( - this.idleStateChangedListener_); - } - if (!chrome.runtime.onStartup.hasListener(this.startupListener_)) - chrome.runtime.onStartup.addListener(this.startupListener_); - } else { - // Not enabled. Shut down if running. - this.shutdownDetector_(); - - chrome.idle.onStateChanged.removeListener( - this.idleStateChangedListener_); - // If hotwording isn't enabled, don't start this component extension on - // Chrome startup. If a user enables hotwording, the status change - // event will be fired and the onStartup event will be registered. - chrome.runtime.onStartup.removeListener(this.startupListener_); - } - }, - - /** - * Starts the hotword detector. - * @private - */ - startDetector_: function() { - // Last attempt to start detector resulted in an error. - if (this.state_ == State_.ERROR) { - // TODO(amistry): Do some error rate tracking here and disable the - // extension if we error too often. - } - - if (!this.pluginManager_) { - this.state_ = State_.STARTING; - var isHotwordStream = this.isAlwaysOnEnabled() && - this.hotwordStatus_.hotwordHardwareAvailable; - this.pluginManager_ = - new hotword.NaClManager(this.loggingEnabled_, isHotwordStream); - this.pluginManager_.addEventListener( - hotword.constants.Event.READY, this.onReady_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.ERROR, this.onError_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.TRIGGER, this.onTrigger_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.TIMEOUT, this.onTimeout_.bind(this)); - this.pluginManager_.addEventListener( - hotword.constants.Event.SPEAKER_MODEL_SAVED, - this.onSpeakerModelSaved_.bind(this)); - chrome.runtime.getPlatformInfo(function(platform) { - var naclArch = platform.nacl_arch; - - // googDucking set to false so that audio output level from other tabs - // is not affected when hotword is enabled. https://crbug.com/357773 - // content/common/media/media_stream_options.cc - // When always-on is enabled, request the hotword stream. - // Optional because we allow power users to bypass the hardware - // detection via a flag, and hence the hotword stream may not be - // available. - var constraints = /** @type {googMediaStreamConstraints} */ - ({ - audio: { - optional: [ - {googDucking: false}, - {googHotword: this.isAlwaysOnEnabled()} - ] - } - }); - navigator.webkitGetUserMedia( - /** @type {MediaStreamConstraints} */ (constraints), - function(stream) { - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.MEDIA_STREAM_RESULT, - hotword.constants.UmaMediaStreamOpenResult.SUCCESS, - hotword.constants.UmaMediaStreamOpenResult.MAX); - // The detector could have been shut down before the stream - // finishes opening. - if (this.pluginManager_ == null) { - stream.getAudioTracks()[0].stop(); - return; - } - - if (this.isAlwaysOnEnabled()) - this.keepAlive_.start(); - if (!this.pluginManager_.initialize(naclArch, stream)) { - this.state_ = State_.ERROR; - this.shutdownPluginManager_(); - } - }.bind(this), - function(error) { - if (error.name in UmaMediaStreamOpenResults_) { - var metricValue = UmaMediaStreamOpenResults_[error.name]; - } else { - var metricValue = - hotword.constants.UmaMediaStreamOpenResult.UNKNOWN; - } - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.MEDIA_STREAM_RESULT, - metricValue, - hotword.constants.UmaMediaStreamOpenResult.MAX); - this.state_ = State_.ERROR; - this.pluginManager_ = null; - }.bind(this)); - }.bind(this)); - } else if (this.state_ != State_.STARTING) { - // Don't try to start a starting detector. - this.startRecognizer_(); - } - }, - - /** - * Start the recognizer plugin. Assumes the plugin has been loaded and is - * ready to start. - * @private - */ - startRecognizer_: function() { - assert(this.pluginManager_, 'No NaCl plugin loaded'); - if (this.state_ != State_.RUNNING) { - this.state_ = State_.RUNNING; - if (this.isAlwaysOnEnabled()) - this.keepAlive_.start(); - this.pluginManager_.startRecognizer(this.startMode_); - } - for (var i = 0; i < this.sessions_.length; i++) { - var session = this.sessions_[i]; - if (session.startedCb_) { - session.startedCb_(); - session.startedCb_ = null; - } - } - }, - - /** - * Stops the hotword detector, if it's running. - * @private - */ - stopDetector_: function() { - this.keepAlive_.stop(); - if (this.pluginManager_ && this.state_ == State_.RUNNING) { - this.state_ = State_.STOPPED; - this.pluginManager_.stopRecognizer(); - } - }, - - /** - * Shuts down and removes the plugin manager, if it exists. - * @private - */ - shutdownPluginManager_: function() { - this.keepAlive_.stop(); - if (this.pluginManager_) { - this.pluginManager_.shutdown(); - this.pluginManager_ = null; - } - }, - - /** - * Shuts down the hotword detector. - * @private - */ - shutdownDetector_: function() { - this.state_ = State_.STOPPED; - this.shutdownPluginManager_(); - }, - - /** - * Finalizes the speaker model. Assumes the plugin has been loaded and - * started. - */ - finalizeSpeakerModel: function() { - assert( - this.pluginManager_, - 'Cannot finalize speaker model: No NaCl plugin loaded'); - if (this.state_ != State_.RUNNING) { - hotword.debug('Cannot finalize speaker model: NaCl plugin not started'); - return; - } - this.pluginManager_.finalizeSpeakerModel(); - }, - - /** - * Handle the hotword plugin being ready to start. - * @private - */ - onReady_: function() { - if (this.state_ != State_.STARTING) { - // At this point, we should not be in the RUNNING state. Doing so would - // imply the hotword detector was started without being ready. - assert(this.state_ != State_.RUNNING, 'Unexpected RUNNING state'); - this.shutdownPluginManager_(); - return; - } - this.startRecognizer_(); - }, - - /** - * Handle an error from the hotword plugin. - * @private - */ - onError_: function() { - this.state_ = State_.ERROR; - this.shutdownPluginManager_(); - }, - - /** - * Handle hotword triggering. - * @param {!Event} event Event containing audio log data. - * @private - */ - onTrigger_: function(event) { - this.keepAlive_.stop(); - hotword.debug('Hotword triggered!'); - chrome.metricsPrivate.recordUserAction( - hotword.constants.UmaMetrics.TRIGGER); - assert(this.pluginManager_, 'No NaCl plugin loaded on trigger'); - // Detector implicitly stops when the hotword is detected. - this.state_ = State_.STOPPED; - - // Play the chime. - this.chime_.play(); - - // Implicitly clear the top session. A session needs to be started in - // order to restart the detector. - if (this.sessions_.length) { - var session = this.sessions_.pop(); - session.triggerCb_(event.log); - - hotword.metrics.recordEnum( - hotword.constants.UmaMetrics.TRIGGER_SOURCE, - UmaTriggerSources_[session.source_], - hotword.constants.UmaTriggerSource.MAX); - } - - // If we're in always-on mode, shut down the hotword detector. The hotword - // stream requires that we close and re-open it after a trigger, and the - // only way to accomplish this is to shut everything down. - if (this.isAlwaysOnEnabled()) - this.shutdownDetector_(); - }, - - /** - * Handle hotword timeout. - * @private - */ - onTimeout_: function() { - hotword.debug('Hotword timeout!'); - - // We get this event when the hotword detector thinks there's a false - // trigger. In this case, we need to shut down and restart the detector to - // re-arm the DSP. - this.shutdownDetector_(); - this.updateStateFromStatus_(); - }, - - /** - * Handle speaker model saved. - * @private - */ - onSpeakerModelSaved_: function() { - hotword.debug('Speaker model saved!'); - - if (this.sessions_.length) { - // Only call the callback of the the top session. - var session = this.sessions_[this.sessions_.length - 1]; - if (session.speakerModelSavedCb_) - session.speakerModelSavedCb_(); - } - }, - - /** - * Remove a hotwording session from the given source. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - * @private - */ - removeSession_: function(source) { - for (var i = 0; i < this.sessions_.length; i++) { - if (this.sessions_[i].source_ == source) { - this.sessions_.splice(i, 1); - break; - } - } - }, - - /** - * Start a hotwording session. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - * @param {!function()} startedCb Callback invoked when the session has - * been started successfully. - * @param {!function()} triggerCb Callback invoked when the hotword has - * @param {function()=} modelSavedCb Callback invoked when the speaker model - * has been saved. - * @param {hotword.constants.RecognizerStartMode=} opt_mode The mode to - * start the recognizer in. - */ - startSession: function( - source, startedCb, triggerCb, opt_modelSavedCb, opt_mode) { - if (this.isTrainingEnabled() && opt_mode) { - this.startMode_ = opt_mode; - } else { - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - } - hotword.debug('Starting session for source: ' + source); - this.removeSession_(source); - this.sessions_.push( - new Session_(source, triggerCb, startedCb, opt_modelSavedCb)); - this.updateStateFromStatus_(); - }, - - /** - * Stops a hotwording session. - * @param {!hotword.constants.SessionSource} source Source of the hotword - * session request. - */ - stopSession: function(source) { - hotword.debug('Stopping session for source: ' + source); - this.removeSession_(source); - // If this is a training session then switch the start mode back to - // normal. - if (source == hotword.constants.SessionSource.TRAINING) - this.startMode_ = hotword.constants.RecognizerStartMode.NORMAL; - this.updateStateFromStatus_(); - }, - - /** - * Handles a chrome.idle.onStateChanged event. - * @param {!string} state State, one of "active", "idle", or "locked". - * @private - */ - handleIdleStateChanged_: function(state) { - hotword.debug('Idle state changed: ' + state); - var oldLocked = this.isLocked_; - if (state == 'locked') - this.isLocked_ = true; - else - this.isLocked_ = false; - - if (oldLocked != this.isLocked_) - this.updateStateFromStatus_(); - }, - - /** - * Handles a chrome.runtime.onStartup event. - * @private - */ - handleStartup_: function() { - // Nothing specific needs to be done here. This function exists solely to - // be registered on the startup event. - } - }; - - return {StateManager: StateManager}; -}); diff --git a/chrome/browser/resources/hotword/training_manager.js b/chrome/browser/resources/hotword/training_manager.js deleted file mode 100644 index f5b68d44885ff..0000000000000 --- a/chrome/browser/resources/hotword/training_manager.js +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -cr.define('hotword', function() { - 'use strict'; - - /** - * Class used to manage speaker training. Starts a hotwording session - * if training is on, and automatically restarts the detector when a - * a hotword is triggered. - * @param {!hotword.StateManager} stateManager - * @constructor - * @extends {hotword.BaseSessionManager} - */ - function TrainingManager(stateManager) { - /** - * Chrome event listeners. Saved so that they can be de-registered when - * hotwording is disabled. - * @private - */ - this.finalizedSpeakerModelListener_ = - this.handleFinalizeSpeakerModel_.bind(this); - - hotword.BaseSessionManager.call( - this, stateManager, hotword.constants.SessionSource.TRAINING); - } - - /** - * Handles a success event on mounting the file system event and deletes - * the user data files. - * @param {FileSystem} fs The FileSystem object. - * @private - */ - TrainingManager.deleteFiles_ = function(fs) { - fs.root.getFile( - hotword.constants.SPEAKER_MODEL_FILE_NAME, {create: false}, - TrainingManager.deleteFile_, TrainingManager.fileErrorHandler_); - - for (var i = 0; i < hotword.constants.NUM_TRAINING_UTTERANCES; ++i) { - fs.root.getFile( - hotword.constants.UTTERANCE_FILE_PREFIX + i + - hotword.constants.UTTERANCE_FILE_EXTENSION, - {create: false}, TrainingManager.deleteFile_, - TrainingManager.fileErrorHandler_); - } - }; - - /** - * Deletes a file. - * @param {FileEntry} fileEntry The FileEntry object. - * @private - */ - TrainingManager.deleteFile_ = function(fileEntry) { - if (fileEntry.isFile) { - hotword.debug('File found: ' + fileEntry.fullPath); - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) { - fileEntry.getMetadata(function(md) { - hotword.debug('File size: ' + md.size); - }); - } - fileEntry.remove(function() { - hotword.debug('File removed: ' + fileEntry.fullPath); - }, TrainingManager.fileErrorHandler_); - } - }; - - /** - * Handles a failure event on mounting the file system event. - * @param {FileError} e The FileError object. - * @private - */ - TrainingManager.fileErrorHandler_ = function(e) { - hotword.debug('File error: ' + e.code); - }; - - /** - * Handles a failure event on checking for the existence of the speaker model. - * @param {FileError} e The FileError object. - * @private - */ - TrainingManager.sendNoSpeakerModelResponse_ = function(e) { - chrome.hotwordPrivate.speakerModelExistsResult(false); - }; - - /** - * Handles a success event on mounting the file system and checks for the - * existence of the speaker model. - * @param {FileSystem} fs The FileSystem object. - * @private - */ - TrainingManager.speakerModelExists_ = function(fs) { - fs.root.getFile( - hotword.constants.SPEAKER_MODEL_FILE_NAME, {create: false}, - TrainingManager.sendSpeakerModelExistsResponse_, - TrainingManager.sendNoSpeakerModelResponse_); - }; - - /** - * Sends a response through the HotwordPrivateApi indicating whether - * the speaker model exists. - * @param {FileEntry} fileEntry The FileEntry object. - * @private - */ - TrainingManager.sendSpeakerModelExistsResponse_ = function(fileEntry) { - if (fileEntry.isFile) { - hotword.debug('File found: ' + fileEntry.fullPath); - if (hotword.DEBUG || window.localStorage['hotword.DEBUG']) { - fileEntry.getMetadata(function(md) { - hotword.debug('File size: ' + md.size); - }); - } - } - chrome.hotwordPrivate.speakerModelExistsResult(fileEntry.isFile); - }; - - /** - * Handles a request to delete the speaker model. - */ - TrainingManager.handleDeleteSpeakerModel = function() { - window.webkitRequestFileSystem( - PERSISTENT, hotword.constants.FILE_SYSTEM_SIZE_BYTES, - TrainingManager.deleteFiles_, TrainingManager.fileErrorHandler_); - }; - - /** - * Handles a request for the speaker model existence. - */ - TrainingManager.handleSpeakerModelExists = function() { - window.webkitRequestFileSystem( - PERSISTENT, hotword.constants.FILE_SYSTEM_SIZE_BYTES, - TrainingManager.speakerModelExists_, TrainingManager.fileErrorHandler_); - }; - - TrainingManager.prototype = { - __proto__: hotword.BaseSessionManager.prototype, - - /** @override */ - enabled: function() { - return this.stateManager.isTrainingEnabled(); - }, - - /** @override */ - updateListeners: function() { - hotword.BaseSessionManager.prototype.updateListeners.call(this); - - if (this.enabled()) { - // Detect when the speaker model needs to be finalized. - if (!chrome.hotwordPrivate.onFinalizeSpeakerModel.hasListener( - this.finalizedSpeakerModelListener_)) { - chrome.hotwordPrivate.onFinalizeSpeakerModel.addListener( - this.finalizedSpeakerModelListener_); - } - this.startSession(hotword.constants.RecognizerStartMode.NEW_MODEL); - } else { - chrome.hotwordPrivate.onFinalizeSpeakerModel.removeListener( - this.finalizedSpeakerModelListener_); - } - }, - - /** @override */ - handleHotwordTrigger: function(log) { - if (this.enabled()) { - hotword.BaseSessionManager.prototype.handleHotwordTrigger.call( - this, log); - this.startSession(hotword.constants.RecognizerStartMode.ADAPT_MODEL); - } - }, - - /** @override */ - startSession: function(opt_mode) { - this.stateManager.startSession( - this.sessionSource_, - function() { - chrome.hotwordPrivate.setHotwordSessionState(true, function() {}); - }, - this.handleHotwordTrigger.bind(this), - this.handleSpeakerModelSaved_.bind(this), opt_mode); - }, - - /** - * Handles a hotwordPrivate.onFinalizeSpeakerModel event. - * @private - */ - handleFinalizeSpeakerModel_: function() { - if (this.enabled()) - this.stateManager.finalizeSpeakerModel(); - }, - - /** - * Handles a hotwordPrivate.onFinalizeSpeakerModel event. - * @private - */ - handleSpeakerModelSaved_: function() { - if (this.enabled()) - chrome.hotwordPrivate.notifySpeakerModelSaved(); - }, - }; - - return {TrainingManager: TrainingManager}; -}); diff --git a/chrome/browser/resources/hotword_audio_verification/OWNERS b/chrome/browser/resources/hotword_audio_verification/OWNERS deleted file mode 100644 index 99e28241baa25..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/OWNERS +++ /dev/null @@ -1 +0,0 @@ -kcarattini@chromium.org diff --git a/chrome/browser/resources/hotword_audio_verification/event_page.js b/chrome/browser/resources/hotword_audio_verification/event_page.js deleted file mode 100644 index ea379d33d9b7d..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/event_page.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var appId = 'hotword_audio_verification'; - -chrome.app.runtime.onLaunched.addListener(function() { - // We need to focus the window if it already exists, since it - // is created as 'hidden'. - // - // Note: If we ever launch on another platform, make sure that this works - // with window managers that support hiding (e.g. Cmd+h on an app window on - // Mac). - var appWindow = chrome.app.window.get(appId); - if (appWindow) { - appWindow.focus(); - return; - } - - chrome.app.window.create('main.html', { - 'frame': 'none', - 'resizable': false, - 'hidden': true, - 'id': appId, - 'innerBounds': {'width': 784, 'height': 448} - }); -}); diff --git a/chrome/browser/resources/hotword_audio_verification/flow.js b/chrome/browser/resources/hotword_audio_verification/flow.js deleted file mode 100644 index c22211492c4e8..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/flow.js +++ /dev/null @@ -1,566 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -(function() { - -// Correspond to steps in the hotword opt-in flow. -/** @const */ var START = 'start-container'; -/** @const */ var AUDIO_HISTORY = 'audio-history-container'; -/** @const */ var SPEECH_TRAINING = 'speech-training-container'; -/** @const */ var FINISH = 'finish-container'; - -/** - * These flows correspond to the three LaunchModes as defined in - * chrome/browser/search/hotword_service.h and should be kept in sync - * with them. - * @const - */ -var FLOWS = [ - [START, SPEECH_TRAINING, FINISH], - [START, AUDIO_HISTORY, SPEECH_TRAINING, FINISH], [SPEECH_TRAINING, FINISH] -]; - -/** - * The launch mode. This enum needs to be kept in sync with that of - * the same name in hotword_service.h. - * @enum {number} - */ -var LaunchMode = {HOTWORD_ONLY: 0, HOTWORD_AND_AUDIO_HISTORY: 1, RETRAIN: 2}; - -/** - * The training state. - * @enum {string} - */ -var TrainingState = { - RESET: 'reset', - TIMEOUT: 'timeout', - ERROR: 'error', -}; - -/** - * Class to control the page flow of the always-on hotword and - * Audio History opt-in process. - * @constructor - */ -function Flow() { - this.currentStepIndex_ = -1; - this.currentFlow_ = []; - - /** - * The mode that this app was launched in. - * @private {LaunchMode} - */ - this.launchMode_ = LaunchMode.HOTWORD_AND_AUDIO_HISTORY; - - /** - * Whether this flow is currently in the process of training a voice model. - * @private {boolean} - */ - this.training_ = false; - - /** - * The current training state. - * @private {?TrainingState} - */ - this.trainingState_ = null; - - /** - * Whether an expected hotword trigger has been received, indexed by - * training step. - * @private {boolean[]} - */ - this.hotwordTriggerReceived_ = []; - - /** - * Prefix of the element ids for the page that is currently training. - * @private {string} - */ - this.trainingPagePrefix_ = 'speech-training'; - - /** - * Whether the speaker model for this flow has been finalized. - * @private {boolean} - */ - this.speakerModelFinalized_ = false; - - /** - * ID of the currently active timeout. - * @private {?number} - */ - this.timeoutId_ = null; - - /** - * Listener for the speakerModelSaved event. - * @private {Function} - */ - this.speakerModelFinalizedListener_ = - this.onSpeakerModelFinalized_.bind(this); - - /** - * Listener for the hotword trigger event. - * @private {Function} - */ - this.hotwordTriggerListener_ = this.handleHotwordTrigger_.bind(this); - - // Listen for the user locking the screen. - chrome.idle.onStateChanged.addListener( - this.handleIdleStateChanged_.bind(this)); - - // Listen for hotword settings changes. This used to detect when the user - // switches to a different profile. - if (chrome.hotwordPrivate.onEnabledChanged) { - chrome.hotwordPrivate.onEnabledChanged.addListener( - this.handleEnabledChanged_.bind(this)); - } -} - -/** - * Advances the current step. Begins training if the speech-training - * page has been reached. - */ -Flow.prototype.advanceStep = function() { - this.currentStepIndex_++; - if (this.currentStepIndex_ < this.currentFlow_.length) { - if (this.currentFlow_[this.currentStepIndex_] == SPEECH_TRAINING) - this.startTraining(); - this.showStep_.apply(this); - } -}; - -/** - * Gets the appropriate flow and displays its first page. - */ -Flow.prototype.startFlow = function() { - if (chrome.hotwordPrivate && chrome.hotwordPrivate.getLaunchState) - chrome.hotwordPrivate.getLaunchState(this.startFlowForMode_.bind(this)); -}; - -/** - * Starts the training process. - */ -Flow.prototype.startTraining = function() { - // Don't start a training session if one already exists. - if (this.training_) - return; - - this.training_ = true; - - if (chrome.hotwordPrivate.onHotwordTriggered && - !chrome.hotwordPrivate.onHotwordTriggered.hasListener( - this.hotwordTriggerListener_)) { - chrome.hotwordPrivate.onHotwordTriggered.addListener( - this.hotwordTriggerListener_); - } - - this.waitForHotwordTrigger_(0); - if (chrome.hotwordPrivate.startTraining) - chrome.hotwordPrivate.startTraining(); -}; - -/** - * Stops the training process. - */ -Flow.prototype.stopTraining = function() { - if (!this.training_) - return; - - this.training_ = false; - if (chrome.hotwordPrivate.onHotwordTriggered) { - chrome.hotwordPrivate.onHotwordTriggered.removeListener( - this.hotwordTriggerListener_); - } - if (chrome.hotwordPrivate.stopTraining) - chrome.hotwordPrivate.stopTraining(); -}; - -/** - * Attempts to enable audio history for the signed-in account. - */ -Flow.prototype.enableAudioHistory = function() { - // Update UI - $('audio-history-agree').disabled = true; - $('audio-history-cancel').disabled = true; - - $('audio-history-error').hidden = true; - $('audio-history-wait').hidden = false; - - if (chrome.hotwordPrivate.setAudioHistoryEnabled) { - chrome.hotwordPrivate.setAudioHistoryEnabled( - true, this.onAudioHistoryRequestCompleted_.bind(this)); - } -}; - -// ---- private methods: - -/** - * Shows an error if the audio history setting was not enabled successfully. - * @private - */ -Flow.prototype.handleAudioHistoryError_ = function() { - $('audio-history-agree').disabled = false; - $('audio-history-cancel').disabled = false; - - $('audio-history-wait').hidden = true; - $('audio-history-error').hidden = false; - - // Set a timeout before focusing the Enable button so that screenreaders - // have time to announce the error first. - this.setTimeout_(function() { - $('audio-history-agree').focus(); - }.bind(this), 50); -}; - -/** - * Callback for when an audio history request completes. - * @param {chrome.hotwordPrivate.AudioHistoryState} state The audio history - * request state. - * @private - */ -Flow.prototype.onAudioHistoryRequestCompleted_ = function(state) { - if (!state.success || !state.enabled) { - this.handleAudioHistoryError_(); - return; - } - - this.advanceStep(); -}; - -/** - * Shows an error if the speaker model has not been finalized. - * @private - */ -Flow.prototype.handleSpeakerModelFinalizedError_ = function() { - if (!this.training_) - return; - - if (this.speakerModelFinalized_) - return; - - this.updateTrainingState_(TrainingState.ERROR); - this.stopTraining(); -}; - -/** - * Handles the speaker model finalized event. - * @private - */ -Flow.prototype.onSpeakerModelFinalized_ = function() { - this.speakerModelFinalized_ = true; - if (chrome.hotwordPrivate.onSpeakerModelSaved) { - chrome.hotwordPrivate.onSpeakerModelSaved.removeListener( - this.speakerModelFinalizedListener_); - } - this.stopTraining(); - this.setTimeout_(this.finishFlow_.bind(this), 2000); -}; - -/** - * Completes the training process. - * @private - */ -Flow.prototype.finishFlow_ = function() { - if (chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled) { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - true, this.advanceStep.bind(this)); - } -}; - -/** - * Handles a user clicking on the retry button. - */ -Flow.prototype.handleRetry = function() { - if (!(this.trainingState_ == TrainingState.TIMEOUT || - this.trainingState_ == TrainingState.ERROR)) - return; - - this.startTraining(); - this.updateTrainingState_(TrainingState.RESET); -}; - -// ---- private methods: - -/** - * Completes the training process. - * @private - */ -Flow.prototype.finalizeSpeakerModel_ = function() { - if (!this.training_) - return; - - // Listen for the success event from the NaCl module. - if (chrome.hotwordPrivate.onSpeakerModelSaved && - !chrome.hotwordPrivate.onSpeakerModelSaved.hasListener( - this.speakerModelFinalizedListener_)) { - chrome.hotwordPrivate.onSpeakerModelSaved.addListener( - this.speakerModelFinalizedListener_); - } - - this.speakerModelFinalized_ = false; - this.setTimeout_(this.handleSpeakerModelFinalizedError_.bind(this), 30000); - if (chrome.hotwordPrivate.finalizeSpeakerModel) - chrome.hotwordPrivate.finalizeSpeakerModel(); -}; - -/** - * Returns the current training step. - * @param {string} curStepClassName The name of the class of the current - * training step. - * @return {Object} The current training step, its index, and an array of - * all training steps. Any of these can be undefined. - * @private - */ -Flow.prototype.getCurrentTrainingStep_ = function(curStepClassName) { - var steps = - $(this.trainingPagePrefix_ + '-training').querySelectorAll('.train'); - var curStep = - $(this.trainingPagePrefix_ + '-training').querySelector('.listening'); - - return { - current: curStep, - index: Array.prototype.indexOf.call(steps, curStep), - steps: steps - }; -}; - -/** - * Updates the training state. - * @param {TrainingState} state The training state. - * @private - */ -Flow.prototype.updateTrainingState_ = function(state) { - this.trainingState_ = state; - this.updateErrorUI_(); -}; - -/** - * Waits two minutes and then checks for a training error. - * @param {number} index The index of the training step. - * @private - */ -Flow.prototype.waitForHotwordTrigger_ = function(index) { - if (!this.training_) - return; - - this.hotwordTriggerReceived_[index] = false; - this.setTimeout_(this.handleTrainingTimeout_.bind(this, index), 120000); -}; - -/** - * Checks for and handles a training error. - * @param {number} index The index of the training step. - * @private - */ -Flow.prototype.handleTrainingTimeout_ = function(index) { - if (this.hotwordTriggerReceived_[index]) - return; - - this.timeoutTraining_(); -}; - -/** - * Times out training and updates the UI to show a "retry" message, if - * currently training. - * @private - */ -Flow.prototype.timeoutTraining_ = function() { - if (!this.training_) - return; - - this.clearTimeout_(); - this.updateTrainingState_(TrainingState.TIMEOUT); - this.stopTraining(); -}; - -/** - * Sets a timeout. If any timeout is active, clear it. - * @param {Function} func The function to invoke when the timeout occurs. - * @param {number} delay Timeout delay in milliseconds. - * @private - */ -Flow.prototype.setTimeout_ = function(func, delay) { - this.clearTimeout_(); - this.timeoutId_ = setTimeout(function() { - this.timeoutId_ = null; - func(); - }, delay); -}; - -/** - * Clears any currently active timeout. - * @private - */ -Flow.prototype.clearTimeout_ = function() { - if (this.timeoutId_ != null) { - clearTimeout(this.timeoutId_); - this.timeoutId_ = null; - } -}; - -/** - * Updates the training error UI. - * @private - */ -Flow.prototype.updateErrorUI_ = function() { - if (!this.training_) - return; - - var trainingSteps = this.getCurrentTrainingStep_('listening'); - var steps = trainingSteps.steps; - - $(this.trainingPagePrefix_ + '-toast').hidden = - this.trainingState_ != TrainingState.TIMEOUT; - if (this.trainingState_ == TrainingState.RESET) { - // We reset the training to begin at the first step. - // The first step is reset to 'listening', while the rest - // are reset to 'not-started'. - var prompt = loadTimeData.getString('trainingFirstPrompt'); - for (var i = 0; i < steps.length; ++i) { - steps[i].classList.remove('recorded'); - if (i == 0) { - steps[i].classList.remove('not-started'); - steps[i].classList.add('listening'); - } else { - steps[i].classList.add('not-started'); - if (i == steps.length - 1) - prompt = loadTimeData.getString('trainingLastPrompt'); - else - prompt = loadTimeData.getString('trainingMiddlePrompt'); - } - steps[i].querySelector('.text').textContent = prompt; - } - - // Reset the buttonbar. - $(this.trainingPagePrefix_ + '-processing').hidden = true; - $(this.trainingPagePrefix_ + '-wait').hidden = false; - $(this.trainingPagePrefix_ + '-error').hidden = true; - $(this.trainingPagePrefix_ + '-retry').hidden = true; - } else if (this.trainingState_ == TrainingState.TIMEOUT) { - var curStep = trainingSteps.current; - if (curStep) { - curStep.classList.remove('listening'); - curStep.classList.add('not-started'); - } - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the timeout first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-toast').children[1].focus(); - }.bind(this), 50); - } else if (this.trainingState_ == TrainingState.ERROR) { - // Update the buttonbar. - $(this.trainingPagePrefix_ + '-wait').hidden = true; - $(this.trainingPagePrefix_ + '-error').hidden = false; - $(this.trainingPagePrefix_ + '-retry').hidden = false; - $(this.trainingPagePrefix_ + '-processing').hidden = false; - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the error first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-retry').children[0].focus(); - }.bind(this), 50); - } -}; - -/** - * Handles a hotword trigger event and updates the training UI. - * @private - */ -Flow.prototype.handleHotwordTrigger_ = function() { - var trainingSteps = this.getCurrentTrainingStep_('listening'); - - if (!trainingSteps.current) - return; - - var index = trainingSteps.index; - this.hotwordTriggerReceived_[index] = true; - - trainingSteps.current.querySelector('.text').textContent = - loadTimeData.getString('trainingRecorded'); - trainingSteps.current.classList.remove('listening'); - trainingSteps.current.classList.add('recorded'); - - if (trainingSteps.steps[index + 1]) { - trainingSteps.steps[index + 1].classList.remove('not-started'); - trainingSteps.steps[index + 1].classList.add('listening'); - this.waitForHotwordTrigger_(index + 1); - return; - } - - // Only the last step makes it here. - var buttonElem = $(this.trainingPagePrefix_ + '-processing').hidden = false; - this.finalizeSpeakerModel_(); -}; - -/** - * Handles a chrome.idle.onStateChanged event and times out the training if - * the state is "locked". - * @param {!string} state State, one of "active", "idle", or "locked". - * @private - */ -Flow.prototype.handleIdleStateChanged_ = function(state) { - if (state == 'locked') - this.timeoutTraining_(); -}; - -/** - * Handles a chrome.hotwordPrivate.onEnabledChanged event and times out - * training if the user is no longer the active user (user switches profiles). - * @private - */ -Flow.prototype.handleEnabledChanged_ = function() { - if (chrome.hotwordPrivate.getStatus) { - chrome.hotwordPrivate.getStatus(function(status) { - if (status.userIsActive) - return; - - this.timeoutTraining_(); - }.bind(this)); - } -}; - -/** - * Gets and starts the appropriate flow for the launch mode. - * @param {chrome.hotwordPrivate.LaunchState} state Launch state of the - * Hotword Audio Verification App. - * @private - */ -Flow.prototype.startFlowForMode_ = function(state) { - this.launchMode_ = state.launchMode; - assert( - state.launchMode >= 0 && state.launchMode < FLOWS.length, - 'Invalid Launch Mode.'); - this.currentFlow_ = FLOWS[state.launchMode]; - if (state.launchMode == LaunchMode.HOTWORD_ONLY) { - $('intro-description-audio-history-enabled').hidden = false; - } else if (state.launchMode == LaunchMode.HOTWORD_AND_AUDIO_HISTORY) { - $('intro-description').hidden = false; - } - - this.advanceStep(); -}; - -/** - * Displays the current step. If the current step is not the first step, - * also hides the previous step. Focuses the current step's first button. - * @private - */ -Flow.prototype.showStep_ = function() { - var currentStepId = this.currentFlow_[this.currentStepIndex_]; - var currentStep = document.getElementById(currentStepId); - currentStep.hidden = false; - - cr.ui.setInitialFocus(currentStep); - - var previousStep = null; - if (this.currentStepIndex_ > 0) - previousStep = this.currentFlow_[this.currentStepIndex_ - 1]; - - if (previousStep) - document.getElementById(previousStep).hidden = true; - - chrome.app.window.current().show(); -}; - -window.Flow = Flow; -})(); diff --git a/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png b/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png deleted file mode 100644 index 6ff742000e818..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/gradient-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png b/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png deleted file mode 100644 index 3c39792f23ccf..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/gradient-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png deleted file mode 100644 index c04541c591b1e..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png deleted file mode 100644 index 7fca135f4b688..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-check-blue-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png deleted file mode 100644 index 1071613cb1bf7..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png deleted file mode 100644 index e93d6e18eb90b..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-check-gray-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png deleted file mode 100644 index f8d7584137597..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-error-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png deleted file mode 100644 index dc0bf4f1c93cc..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-error-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png deleted file mode 100644 index 23d17c9c322f1..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png b/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png deleted file mode 100644 index 63cf9729d3462..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/ic-x-white-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-128.png b/chrome/browser/resources/hotword_audio_verification/images/icon-128.png deleted file mode 100644 index d3a010c5376d9..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/icon-128.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-16.png b/chrome/browser/resources/hotword_audio_verification/images/icon-16.png deleted file mode 100644 index 3a7caeb0c2f61..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/icon-16.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/icon-48.png b/chrome/browser/resources/hotword_audio_verification/images/icon-48.png deleted file mode 100644 index 1f48e48098e7f..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/icon-48.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png b/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png deleted file mode 100644 index 3190980fbf90e..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/intro-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png b/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png deleted file mode 100644 index 6465825b0ae11..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/intro-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png b/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png deleted file mode 100644 index 0bb41bc244e9e..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-1x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png b/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png deleted file mode 100644 index cd1ffa7205be3..0000000000000 Binary files a/chrome/browser/resources/hotword_audio_verification/images/placeholder-loader-2x.png and /dev/null differ diff --git a/chrome/browser/resources/hotword_audio_verification/main.html b/chrome/browser/resources/hotword_audio_verification/main.html deleted file mode 100644 index 2572c9464c951..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/main.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - -
- - - - -
- - diff --git a/chrome/browser/resources/hotword_audio_verification/main.js b/chrome/browser/resources/hotword_audio_verification/main.js deleted file mode 100644 index 33fc21a9ec493..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/main.js +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var appWindow = chrome.app.window.current(); - -document.addEventListener('DOMContentLoaded', function() { - chrome.hotwordPrivate.getLocalizedStrings(function(strings) { - loadTimeData.data = strings; - i18nTemplate.process(document, loadTimeData); - - var flow = new Flow(); - flow.startFlow(); - - var pressFunction = function(e) { - // Only respond to 'Enter' key presses. - if (e.type == 'keyup' && e.key != 'Enter') - return; - - var classes = e.target.classList; - if (classes.contains('close') || classes.contains('finish-button')) { - flow.stopTraining(); - appWindow.close(); - e.preventDefault(); - } - if (classes.contains('retry-button')) { - flow.handleRetry(); - e.preventDefault(); - } - }; - - $('steps').addEventListener('click', pressFunction); - $('steps').addEventListener('keyup', pressFunction); - - $('audio-history-agree').addEventListener('click', function(e) { - flow.enableAudioHistory(); - e.preventDefault(); - }); - - $('hotword-start').addEventListener('click', function(e) { - flow.advanceStep(); - e.preventDefault(); - }); - - $('settings-link').addEventListener('click', function(e) { - chrome.browser.openTab({'url': 'chrome://settings'}, function() {}); - e.preventDefault(); - }); - }); -}); diff --git a/chrome/browser/resources/hotword_audio_verification/manifest.json b/chrome/browser/resources/hotword_audio_verification/manifest.json deleted file mode 100644 index a6e4091e39caf..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/manifest.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - // chrome-extension://abjokfonkihficiokmkfboogholifghn/ - "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtfVZc80kw93gaZwHGhOLpxGKil8n/x1IQ2L/Oj76YeICJk5w4YKw+0N2IYA0gJnwqJdTu3ijrWqO2oQTWoZ3lHmAv9NHsUXHdrWuoGRuVqo0dakLnS+AB3rLGPSerZZNExpdK0Yd3wR6GMOJAoAQM9H6Zpo7LNYjPebx31QJZ6OgdYZA+Eu4fGIJkWIPY1LMsVO1jzFJ4JSPyNWmhxL4fHfQXVM5p1cgJSVxTXsB1ZGaRc4HF2kwSYMOimIiWqfU0VInTXVU7IS3hJaKzm/LExW/ABTGejf2sGIa725EQTavGFsQ07jFZdVzKGAjHCU/0Jy8PxDIg2B+ixlM2QXP/wIDAQAB", - "name": "Ok Google", - "version": "0.1", - "manifest_version": 2, - "icons": { - "16": "images/icon-16.png", - "48": "images/icon-48.png", - "128": "images/icon-128.png" - }, - "app": { - "background": { - "scripts": ["event_page.js"], - "persistent": false - }, - "content_security_policy": "default-src 'self' blob: filesystem:; script-src 'self' blob: filesystem: chrome://resources chrome://settings; style-src 'self' blob: filesystem: chrome://resources" - }, - "permissions": [ - "chrome://resources/", - "chrome://settings/", - "browser", - "hotwordPrivate", - "idle" - ], - "display_in_launcher": false -} diff --git a/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html b/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html deleted file mode 100644 index 8c2304ba9abce..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/audio_history_step.html +++ /dev/null @@ -1,38 +0,0 @@ - diff --git a/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html b/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html deleted file mode 100644 index 71537dd45aa33..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/finished_step.html +++ /dev/null @@ -1,30 +0,0 @@ - diff --git a/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html b/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html deleted file mode 100644 index fd37331147a62..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/speech_training_step.html +++ /dev/null @@ -1,56 +0,0 @@ - diff --git a/chrome/browser/resources/hotword_audio_verification/steps/start_step.html b/chrome/browser/resources/hotword_audio_verification/steps/start_step.html deleted file mode 100644 index 441ae6b86aaa6..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/steps/start_step.html +++ /dev/null @@ -1,17 +0,0 @@ - diff --git a/chrome/browser/resources/hotword_audio_verification/style.css b/chrome/browser/resources/hotword_audio_verification/style.css deleted file mode 100644 index 233ad3143f78b..0000000000000 --- a/chrome/browser/resources/hotword_audio_verification/style.css +++ /dev/null @@ -1,361 +0,0 @@ -/* Copyright 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* TODO(xdai): Remove hard-coded font-family for 'Roboto'. */ - -* { - box-sizing: border-box; - color: rgba(0, 0, 0, .54); - font-family: Roboto, 'Noto Sans', sans-serif; - font-size: 13px; - margin: 0; - padding: 0; -} - -#start-container * { - color: #fff; -} - -#start-container h2 { - font-size: 15px; - font-weight: normal; - line-height: 24px; - margin-top: 16px; -} - -#start-container h3 { - font-weight: normal; - margin: 42px 16px 24px 16px; -} - -#start-container div.container { - background: rgb(66, 133, 244); -} - -div.intro-image { - background: -webkit-image-set( - url(../images/intro-1x.png) 1x, - url(../images/intro-2x.png) 2x) - no-repeat; - height: 152px; - left: 24px; - position: absolute; - top: 122px; - width: 304px; -} - -div.intro-text { - left: 328px; - position: absolute; - text-align: center; - top: 116px; - width: 432px; -} - -#start-container div.buttonbar { - background-color: rgb(51, 103, 214); - height: 56px; - padding: 0; - text-align: center; -} - -#start-container .buttonbar button { - height: 100%; - margin: 0; - padding: 0 8px; - width: 100%; -} - -a { - -webkit-app-region: no-drag; - color: rgb(51, 103, 214); - text-decoration: none; -} - -button { - -webkit-app-region: no-drag; -} - -body { - -webkit-app-region: drag; - background: #ddd; -} - -h1 { - font-size: 20px; - font-weight: normal; - line-height: 32px; -} - -h3 { - font-size: 13px; - line-height: 20px; -} - -div.container { - background: #fff; - height: 448px; - position: relative; - width: 784px; -} - -div.header { - background: -webkit-image-set( - url(../images/gradient-1x.png) 1x, - url(../images/gradient-2x.png) 2x) - no-repeat; - height: 128px; - padding: 70px 42px 0 42px; -} - -div.header h1 { - color: #fff; -} - -div.content { - height: 264px; - line-height: 20px; - padding: 32px 42px 0 42px; -} - -div.content h3 { - color: rgba(0, 0, 0, .87); - margin-bottom: 16px; -} - -div.col-2 { - color: rgba(0, 0, 0, .54); - float: left; - width: 320px; -} - -div.col-spacing { - float: left; - height: 216px; - width: 60px; -} - -div.v-spacing { - height: 8px; -} - -a[is='action-link'] { - display: inline-block; - font-size: 14px; - margin-top: 22px; - text-decoration: none; - text-transform: uppercase; -} - -.train { - clear: both; - line-height: 18px; - margin-bottom: 24px; -} - -.train .icon { - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.train .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - line-height: 13px; - padding-top: 3px; - vertical-align: top; -} - -.train.recorded .text { - color: rgba(66, 133, 244, 1); -} - -@keyframes rotate { - from { transform: rotate(0); } - to { transform: rotate(359deg); } -} - -.train.listening .icon { - animation: rotate 2s linear infinite; - background: -webkit-image-set( - url(../images/placeholder-loader-1x.png) 1x, - url(../images/placeholder-loader-2x.png) 2x) - no-repeat; -} - -.train.not-started .icon { - background: -webkit-image-set( - url(../images/ic-check-gray-1x.png) 1x, - url(../images/ic-check-gray-2x.png) 2x) - no-repeat; -} - -.train.recorded .icon { - background: -webkit-image-set( - url(../images/ic-check-blue-1x.png) 1x, - url(../images/ic-check-blue-2x.png) 2x) - no-repeat; -} - -.check { - clear: both; - height: 18px; - margin-bottom: 24px; -} - -.check .icon { - background: -webkit-image-set( - url(../images/ic-check-blue-1x.png) 1x, - url(../images/ic-check-blue-2x.png) 2x) - no-repeat; - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.check .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - height: 18px; - line-height: 18px; - padding-top: 2px; - vertical-align: top; -} - -div.buttonbar { - background-color: rgba(236,239, 241, 1); - bottom: 0; - height: 56px; - padding: 12px; - position: absolute; - width: 100%; -} - -.buttonbar button { - background: none; - border: none; - display: inline-block; - font-weight: 700; - height: 32px; - line-height: 32px; - margin-left: 8px; - min-width: 56px; - padding: 1px 8px 0 8px; - text-transform: uppercase; -} - -.buttonbar button:disabled { - opacity: .5; -} - -.buttonbar button.grayed-out { - color: rgba(0, 0, 0, .28); - text-transform: none; -} - -.buttonbar button.primary { - color: rgb(51, 103, 214); -} - -.buttonbar .left { - float: left; - text-align: left; -} - -.buttonbar .left button:first-child { - margin-left: 0; -} - -.buttonbar .right { - float: right; - text-align: right; -} - -.buttonbar .message { - margin: 7px 0 0 2px; -} - -.buttonbar .message .icon { - display: inline-block; - height: 18px; - margin-right: 8px; - vertical-align: top; - width: 18px; -} - -.buttonbar .message.wait .icon { - animation: rotate 2s linear infinite; - background: -webkit-image-set( - url(../images/placeholder-loader-1x.png) 1x, - url(../images/placeholder-loader-2x.png) 2x) - no-repeat; -} - -.buttonbar .message.error .icon { - background: -webkit-image-set( - url(../images/ic-error-1x.png) 1x, - url(../images/ic-error-2x.png) 2x) - no-repeat; -} - -.buttonbar .message .text { - color: rgba(0, 0, 0, .54); - display: inline-block; - line-height: 18px; - padding-top: 2px; - vertical-align: top; -} - -.buttonbar .message.error .text { - color: rgb(213, 0, 0); -} - -.close { - -webkit-app-region: no-drag; - background: -webkit-image-set( - url(../images/ic-x-white-1x.png) 1x, - url(../images/ic-x-white-2x.png) 2x) - center center no-repeat; - border: none; - float: right; - height: 42px; - opacity: .54; - width: 42px; -} - -.close:hover { - opacity: 1; -} - -.toast { - background-color: rgb(38, 50, 56); - bottom: 0; - height: 52px; - padding: 10px 12px 0 42px; - position: absolute; - width: 100%; -} - -.toast .message { - color: #fff; - float: left; - padding: 9px 0 0 0; -} - -.toast button { - background: none; - border: none; - color: rgb(58, 218, 255); - float: right; - height: 32px; - margin-left: 18px; - min-width: 56px; - padding: 0 8px 0 8px; - text-transform: uppercase; -} diff --git a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js index 947dcbefc3994..27db88365fa1f 100644 --- a/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js +++ b/chrome/browser/resources/settings/search_engines_page/search_engines_browser_proxy.js @@ -37,18 +37,6 @@ var SearchEngine; */ var SearchEnginesInfo; -/** - * @typedef {{ - * allowed: boolean, - * enabled: boolean, - * alwaysOn: boolean, - * errorMessage: string, - * userName: string, - * historyEnabled: boolean - * }} - */ -var SearchPageHotwordInfo; - cr.define('settings', function() { /** @interface */ class SearchEnginesBrowserProxy { @@ -80,12 +68,6 @@ cr.define('settings', function() { */ validateSearchEngineInput(fieldName, fieldValue) {} - /** @return {!Promise} */ - getHotwordInfo() {} - - /** @param {boolean} enabled */ - setHotwordSearchEnabled(enabled) {} - turnOnGoogleAssistant() {} } @@ -133,16 +115,6 @@ cr.define('settings', function() { 'validateSearchEngineInput', fieldName, fieldValue); } - /** @override */ - getHotwordInfo() { - return cr.sendWithPromise('getHotwordInfo'); - } - - /** @override */ - setHotwordSearchEnabled(enabled) { - chrome.send('setHotwordSearchEnabled', [enabled]); - } - /** @override */ turnOnGoogleAssistant() { chrome.send('turnOnGoogleAssistant'); diff --git a/chrome/browser/resources/settings/search_page/search_page.html b/chrome/browser/resources/settings/search_page/search_page.html index e10d814133037..1e9f88f1e7ca6 100644 --- a/chrome/browser/resources/settings/search_page/search_page.html +++ b/chrome/browser/resources/settings/search_page/search_page.html @@ -82,62 +82,6 @@ - - - - - -
diff --git a/chrome/browser/resources/settings/search_page/search_page.js b/chrome/browser/resources/settings/search_page/search_page.js index 3dbfcf19d690f..9a3d913e9696c 100644 --- a/chrome/browser/resources/settings/search_page/search_page.js +++ b/chrome/browser/resources/settings/search_page/search_page.js @@ -34,18 +34,6 @@ Polymer({ /** @private Filter applied to search engines. */ searchEnginesFilter_: String, - /** @private {!SearchPageHotwordInfo|undefined} */ - hotwordInfo_: Object, - - /** - * This is a local PrefObject used to reflect the enabled state of hotword - * search. It is not tied directly to a pref. (There are two prefs - * associated with state and they do not map directly to whether or not - * hotword search is actually enabled). - * @private {!chrome.settingsPrivate.PrefObject|undefined} - */ - hotwordSearchEnablePref_: Object, - /** @type {?Map} */ focusConfig_: Object, @@ -80,15 +68,10 @@ Polymer({ // Omnibox search engine var updateSearchEngines = searchEngines => { this.set('searchEngines_', searchEngines.defaults); - this.requestHotwordInfoUpdate_(); }; this.browserProxy_.getSearchEnginesList().then(updateSearchEngines); cr.addWebUIListener('search-engines-changed', updateSearchEngines); - // Hotword (OK Google) listener - cr.addWebUIListener( - 'hotword-info-update', this.hotwordInfoUpdate_.bind(this)); - this.focusConfig_ = new Map(); if (settings.routes.SEARCH_ENGINES) { this.focusConfig_.set( @@ -139,68 +122,6 @@ Polymer({ }, // - /** - * @param {!Event} event - * @private - */ - onHotwordSearchEnableChange_: function(event) { - // Do not set the pref directly, allow Chrome to run the setup app instead. - this.browserProxy_.setHotwordSearchEnabled( - !!this.hotwordSearchEnablePref_.value); - }, - - /** @private */ - requestHotwordInfoUpdate_: function() { - this.browserProxy_.getHotwordInfo().then(hotwordInfo => { - this.hotwordInfoUpdate_(hotwordInfo); - }); - }, - - /** - * @param {!SearchPageHotwordInfo} hotwordInfo - * @private - */ - hotwordInfoUpdate_: function(hotwordInfo) { - this.hotwordInfo_ = hotwordInfo; - this.hotwordSearchEnablePref_ = { - key: 'unused', // required for PrefObject - type: chrome.settingsPrivate.PrefType.BOOLEAN, - value: this.hotwordInfo_.enabled, - }; - }, - - /** - * @return {string} - * @private - */ - getHotwordSearchEnableSubLabel_: function() { - return this.i18n( - this.hotwordInfo_.alwaysOn ? 'searchOkGoogleSubtextAlwaysOn' : - 'searchOkGoogleSubtextNoHardware'); - }, - - /** - * @return {boolean} - * @private - */ - getShowHotwordSearchRetrain_: function() { - return this.hotwordInfo_.enabled && this.hotwordInfo_.alwaysOn; - }, - - /** - * @return {boolean} True if the pref is enabled but hotword is not. - * @private - */ - getShowHotwordError_: function() { - return this.hotwordInfo_.enabled && !!this.hotwordInfo_.errorMessage; - }, - - /** @private */ - onRetrainTap_: function() { - // Re-enable hotword search enable; this will trigger the retrain UI. - this.browserProxy_.setHotwordSearchEnabled(this.hotwordInfo_.enabled); - }, - // /** * @param {boolean} toggleValue diff --git a/chrome/browser/search/OWNERS b/chrome/browser/search/OWNERS index b97f2a3e3d628..a8188f97d801c 100644 --- a/chrome/browser/search/OWNERS +++ b/chrome/browser/search/OWNERS @@ -1,7 +1,5 @@ file://components/search/OWNERS -per-file hotword*=mgiuca@chromium.org -per-file hotword*=kcarattini@chromium.org per-file *source*=mathp@chromium.org per-file *source*=fserb@chromium.org per-file *source*=huangs@chromium.org diff --git a/chrome/browser/search/hotword_audio_history_handler.cc b/chrome/browser/search/hotword_audio_history_handler.cc deleted file mode 100644 index 8b240a3fdab37..0000000000000 --- a/chrome/browser/search/hotword_audio_history_handler.cc +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_audio_history_handler.h" - -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/history/web_history_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/pref_names.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" - -using extensions::BrowserContextKeyedAPIFactory; -using extensions::HotwordPrivateEventService; - -// Max number of hours between audio history checks. -static const int kHoursUntilNextAudioHistoryCheck = 24; - -HotwordAudioHistoryHandler::HotwordAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr& task_runner) - : task_runner_(task_runner), - profile_(Profile::FromBrowserContext(context)), - weak_ptr_factory_(this) { -} - -HotwordAudioHistoryHandler::~HotwordAudioHistoryHandler() { -} - -history::WebHistoryService* HotwordAudioHistoryHandler::GetWebHistory() { - return WebHistoryServiceFactory::GetForProfile(profile_); -} - -void HotwordAudioHistoryHandler::UpdateAudioHistoryState() { - GetAudioHistoryEnabled( - base::Bind(&HotwordAudioHistoryHandler::UpdateLocalPreference, - weak_ptr_factory_.GetWeakPtr())); - // Set the function to update in a day. - task_runner_->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordAudioHistoryHandler::UpdateAudioHistoryState, - weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromHours(kHoursUntilNextAudioHistoryCheck)); -} - -void HotwordAudioHistoryHandler::UpdateLocalPreference( - bool success, bool new_enabled_value) { - if (success) { - PrefService* prefs = profile_->GetPrefs(); - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, new_enabled_value); - } -} - -void HotwordAudioHistoryHandler::GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback) { -// Please add network traffic annotation if you want to remove this #if. -#if defined(OS_CHROMEOS) - history::WebHistoryService* web_history = GetWebHistory(); - if (web_history) { - web_history->GetAudioHistoryEnabled( - base::Bind(&HotwordAudioHistoryHandler::GetAudioHistoryComplete, - weak_ptr_factory_.GetWeakPtr(), callback), - NO_PARTIAL_TRAFFIC_ANNOTATION_YET); - } else { - // If web_history is null, the user is not signed in. Set the opt-in value - // to the last known value and run the callback with false for success. - PrefService* prefs = profile_->GetPrefs(); - callback.Run(false, prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); - } -#else - NOTREACHED() - << ": This functions is supposed to be called only in Chrome OS."; -#endif // defined(OS_CHROMEOS) -} - -void HotwordAudioHistoryHandler::SetAudioHistoryEnabled( - const bool enabled, - const HotwordAudioHistoryCallback& callback) { -// Please add network traffic annotation if you want to remove this #if. -#if defined(OS_CHROMEOS) - history::WebHistoryService* web_history = GetWebHistory(); - if (web_history) { - web_history->SetAudioHistoryEnabled( - enabled, - base::Bind(&HotwordAudioHistoryHandler::SetAudioHistoryComplete, - weak_ptr_factory_.GetWeakPtr(), enabled, callback), - NO_PARTIAL_TRAFFIC_ANNOTATION_YET); - } else { - // If web_history is null, run the callback with false for success - // and return the last known value for the opt-in pref. - PrefService* prefs = profile_->GetPrefs(); - callback.Run(false, prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); - } -#else - NOTREACHED() - << ": This functions is supposed to be called only in Chrome OS."; -#endif // defined(OS_CHROMEOS) -} - -void HotwordAudioHistoryHandler::GetAudioHistoryComplete( - const HotwordAudioHistoryCallback& callback, - bool success, bool new_enabled_value) { - // Initialize value to the last known value of the audio history pref. - PrefService* prefs = profile_->GetPrefs(); - bool value = prefs->GetBoolean(prefs::kHotwordAudioLoggingEnabled); - // If the call was successful, use the new value for updates. - if (success) { - value = new_enabled_value; - prefs->SetBoolean(prefs::kHotwordAudioLoggingEnabled, value); - // If the setting is now turned off, always on should also be turned off, - // and the speaker model should be deleted. - if (!value) { - if (prefs->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled)) { - prefs->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, false); - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get( - profile_); - if (event_service) - event_service->OnDeleteSpeakerModel(); - } - } - } - callback.Run(success, value); -} - -void HotwordAudioHistoryHandler::SetAudioHistoryComplete( - bool new_enabled_value, - const HotwordAudioHistoryCallback& callback, - bool success, bool callback_enabled_value) { - UpdateLocalPreference(success, new_enabled_value); - callback.Run(success, new_enabled_value); -} diff --git a/chrome/browser/search/hotword_audio_history_handler.h b/chrome/browser/search/hotword_audio_history_handler.h deleted file mode 100644 index 8126b572469fd..0000000000000 --- a/chrome/browser/search/hotword_audio_history_handler.h +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_ - -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "components/prefs/pref_change_registrar.h" -#include "content/public/browser/browser_context.h" - -class Profile; - -namespace base { -class SingleThreadTaskRunner; -} - -namespace history { -class WebHistoryService; -} - -// A class which handles the audio history pref for hotwording. This has been -// pulled into its own class in order to transparently (to the rest of -// hotwording) handle changing user global pref management systems. -class HotwordAudioHistoryHandler { - public: - typedef base::Callback - HotwordAudioHistoryCallback; - - HotwordAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr& task_runner); - - virtual ~HotwordAudioHistoryHandler(); - - // Initiates a call to get the updated audio history state. - void UpdateAudioHistoryState(); - - // Updates the current preference value based on the user's account info - // or false if the user is not signed in. - virtual void GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback); - - // Sets the user's global pref value for enabling audio history. - void SetAudioHistoryEnabled(const bool enabled, - const HotwordAudioHistoryCallback& callback); - - // This helper function is made public for testing. - virtual history::WebHistoryService* GetWebHistory(); - - private: - // Helper function used as a callback and to factor out common code. - void UpdateLocalPreference(bool success, bool new_enabled_value); - - // Called upon completion of web history->GetAudioHistoryEnabled. - void GetAudioHistoryComplete( - const HotwordAudioHistoryCallback& callback, - bool success, - bool new_enabled_value); - - // Called upon completion of web history->SetAudioHistoryEnabled. - // |new_enabled_value| is the desired value of the preference. - // |callback_enabled_value| should not be considered valid. - void SetAudioHistoryComplete( - bool new_enabled_value, - const HotwordAudioHistoryCallback& callback, - bool success, - bool callback_enabled_value); - - scoped_refptr task_runner_; - - Profile* profile_; - - base::WeakPtrFactory weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(HotwordAudioHistoryHandler); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_AUDIO_HISTORY_HANDLER_H_ diff --git a/chrome/browser/search/hotword_client.h b/chrome/browser/search/hotword_client.h deleted file mode 100644 index 13d2f35e5623f..0000000000000 --- a/chrome/browser/search/hotword_client.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_ - -#include "base/memory/ref_counted.h" - -namespace content { -struct SpeechRecognitionSessionPreamble; -} - -class HotwordClient { - public: - virtual ~HotwordClient() {} - - // Called when the hotword recognition session state has been changed. - virtual void OnHotwordStateChanged(bool started) {} - - // Called when the hotword is recognized. - virtual void OnHotwordRecognized( - const scoped_refptr& preamble) - = 0; -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_CLIENT_H_ diff --git a/chrome/browser/search/hotword_installer_browsertest.cc b/chrome/browser/search/hotword_installer_browsertest.cc deleted file mode 100644 index 2aa7eead0e39e..0000000000000 --- a/chrome/browser/search/hotword_installer_browsertest.cc +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include - -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/webstore_startup_installer.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/extensions/webstore_install_result.h" -#include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { -class MockHotwordWebstoreInstaller - : public HotwordService::HotwordWebstoreInstaller { - public: - MockHotwordWebstoreInstaller(Profile* profile, const Callback& callback) - : HotwordService::HotwordWebstoreInstaller( - extension_misc::kHotwordSharedModuleId, - profile, - callback) { - } - - const GURL& GetRequestorURL() const override { - // This should not be valid so it hangs. - return GURL::EmptyGURL(); - } - - void BeginInstall() { - WebstoreStandaloneInstaller::BeginInstall(); - } - - private: - ~MockHotwordWebstoreInstaller() override {} -}; - - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), - profile_(profile), - weak_factory_(this) { - } - - void InstallHotwordExtensionFromWebstore(int num_tries) override { - installer_ = new MockHotwordWebstoreInstaller( - profile_, - base::Bind(&MockHotwordService::InstallerCallback, - weak_factory_.GetWeakPtr(), - num_tries - 1)); - installer_->BeginInstall(); - } - - void InstallerCallback(int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result) { - } - - private: - Profile* profile_; - base::WeakPtrFactory weak_factory_; -}; - -std::unique_ptr BuildMockHotwordService( - content::BrowserContext* context) { - return base::MakeUnique(static_cast(context)); -} - -} // namespace - -namespace extensions { - -class HotwordInstallerBrowserTest : public ExtensionBrowserTest { - public: - HotwordInstallerBrowserTest() {} - ~HotwordInstallerBrowserTest() override {} - - private: - DISALLOW_COPY_AND_ASSIGN(HotwordInstallerBrowserTest); -}; - -// Disabled on Windows due to https://crbug.com/717648. Since the installation -// is still in progress during shutdown, file handles may still be open. This -// causes TestingProfile to crash during shutdown. -#if defined(OS_WIN) -#define Maybe_AbortInstallOnShutdown DISABLED_AbortInstallOnShutdown -#else -#define Maybe_AbortInstallOnShutdown AbortInstallOnShutdown -#endif -// Test that installing to a non-existent URL (which should hang) does not -// crash. This test is successful if it does not crash and trigger any DCHECKS. -IN_PROC_BROWSER_TEST_F(HotwordInstallerBrowserTest, - Maybe_AbortInstallOnShutdown) { - TestingProfile test_profile; - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - &test_profile, BuildMockHotwordService)); - hotword_service->InstallHotwordExtensionFromWebstore(1); -} - -} // namespace extensions diff --git a/chrome/browser/search/hotword_service.cc b/chrome/browser/search/hotword_service.cc deleted file mode 100644 index a19cdfe5cda3d..0000000000000 --- a/chrome/browser/search/hotword_service.cc +++ /dev/null @@ -1,883 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service.h" - -#include - -#include - -#include "base/command_line.h" -#include "base/i18n/case_conversion.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram_macros.h" -#include "base/metrics/sparse_histogram.h" -#include "base/path_service.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/pending_extension_manager.h" -#include "chrome/browser/extensions/updater/extension_updater.h" -#include "chrome/browser/notifications/notification_ui_manager.h" -#include "chrome/browser/plugins/plugin_prefs.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/pref_names.h" -#include "chrome/grit/generated_resources.h" -#include "chrome/grit/theme_resources.h" -#include "components/language_usage_metrics/language_usage_metrics.h" -#include "components/prefs/pref_service.h" -#include "components/user_manager/user.h" -#include "components/user_manager/user_manager.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/plugin_service.h" -#include "content/public/common/webplugininfo.h" -#include "extensions/browser/extension_system.h" -#include "extensions/browser/uninstall_reason.h" -#include "extensions/common/disable_reason.h" -#include "extensions/common/one_shot_event.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/message_center/notification.h" - -#if defined(OS_CHROMEOS) -#include "chromeos/audio/cras_audio_handler.h" -#endif - -using extensions::BrowserContextKeyedAPIFactory; -using extensions::HotwordPrivateEventService; - -namespace { - -// Allowed locales for hotwording. Note that Chrome does not support all of -// these locales, condensing them to their 2-letter equivalent, but the full -// list is here for completeness and testing. -static const char* kSupportedLocales[] = { - "en", - "en_au", - "en_ca", - "en_gb", - "en_nz", - "en_us", - "en_za", - "de", - "de_at", - "de_de", - "es", - "es_419", - "es_es", - "fr", - "fr_fr", - "it", - "it_it", - "ja", - "ja_jp", - "ko", - "ko_kr", - "pt_br", - "ru", - "ru_ru" -}; - -// Maximum number of retries for installing the hotword shared module from the -// web store. -static const int kMaxInstallRetries = 2; - -// Delay between retries for installing the hotword shared module from the web -// store. -static const int kInstallRetryDelaySeconds = 5; - -// The extension id of the old hotword voice search trigger extension. -const char kHotwordOldExtensionId[] = "bepbmhgboaologfdajaanbcjmnhjmhfn"; - -// Enum describing the state of the hotword preference. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordEnabled { - UNSET = 0, // No hotword preference has been set. - ENABLED, // The (classic) hotword preference is enabled. - DISABLED, // All hotwording is disabled. - ALWAYS_ON_ENABLED, // Always-on hotwording is enabled. - NUM_HOTWORD_ENABLED_METRICS -}; - -// Enum describing the availability state of the hotword extension. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordExtensionAvailability { - UNAVAILABLE = 0, - AVAILABLE, - PENDING_DOWNLOAD, - DISABLED_EXTENSION, - NUM_HOTWORD_EXTENSION_AVAILABILITY_METRICS -}; - -// Enum describing the types of errors that can arise when determining -// if hotwording can be used. NO_ERROR is used so it can be seen how often -// errors arise relative to when they do not. -// This is used for UMA stats -- do not reorder or delete items; only add to -// the end. -enum HotwordError { - NO_HOTWORD_ERROR = 0, - GENERIC_HOTWORD_ERROR, - NACL_HOTWORD_ERROR, - MICROPHONE_HOTWORD_ERROR, - NUM_HOTWORD_ERROR_METRICS -}; - -void RecordLoggingMetrics(Profile* profile) { - // If the user is not opted in to hotword voice search, the audio logging - // metric is not valid so it is not recorded. - if (!profile->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)) - return; - - UMA_HISTOGRAM_BOOLEAN( - "Hotword.HotwordAudioLogging", - profile->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled)); -} - -void RecordErrorMetrics(int error_message) { - HotwordError error = NO_HOTWORD_ERROR; - switch (error_message) { - case IDS_HOTWORD_GENERIC_ERROR_MESSAGE: - error = GENERIC_HOTWORD_ERROR; - break; - case IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE: - error = NACL_HOTWORD_ERROR; - break; - case IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE: - error = MICROPHONE_HOTWORD_ERROR; - break; - default: - error = NO_HOTWORD_ERROR; - } - - UMA_HISTOGRAM_ENUMERATION("Hotword.HotwordError", - error, - NUM_HOTWORD_ERROR_METRICS); -} - -void RecordHotwordEnabledMetric(HotwordService *service, Profile* profile) { - HotwordEnabled enabled_state = DISABLED; - auto* prefs = profile->GetPrefs(); - if (!prefs->HasPrefPath(prefs::kHotwordSearchEnabled) && - !prefs->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled)) { - enabled_state = UNSET; - } else if (service->IsAlwaysOnEnabled()) { - enabled_state = ALWAYS_ON_ENABLED; - } else if (prefs->GetBoolean(prefs::kHotwordSearchEnabled)) { - enabled_state = ENABLED; - } - UMA_HISTOGRAM_ENUMERATION("Hotword.Enabled", enabled_state, - NUM_HOTWORD_ENABLED_METRICS); -} - -ExtensionService* GetExtensionService(Profile* profile) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile); - return extension_system ? extension_system->extension_service() : NULL; -} - -std::string GetCurrentLocale(Profile* profile) { -#if defined(OS_CHROMEOS) - std::string profile_locale = - profile->GetPrefs()->GetString(prefs::kApplicationLocale); - if (!profile_locale.empty()) { - // On ChromeOS locale is per-profile, but only if set. - return profile_locale; - } -#endif - return g_browser_process->GetApplicationLocale(); -} - -} // namespace - -namespace hotword_internal { -// String passed to indicate the training state has changed. -const char kHotwordTrainingEnabled[] = "hotword_training_enabled"; -// Id of the hotword notification. -const char kHotwordNotificationId[] = "hotword"; -// Notifier id for the hotword notification. -const char kHotwordNotifierId[] = "hotword.notification"; -} // namespace hotword_internal - -// Delegate for the hotword notification. -class HotwordNotificationDelegate - : public message_center::NotificationDelegate { - public: - explicit HotwordNotificationDelegate(Profile* profile) : profile_(profile) {} - - // Overridden from NotificationDelegate: - void ButtonClick(int button_index) override { - DCHECK_EQ(0, button_index); - Click(); - } - - void Click() override { - // Launch the hotword audio verification app in the right mode. - HotwordService::LaunchMode launch_mode = - HotwordService::HOTWORD_AND_AUDIO_HISTORY; - if (profile_->GetPrefs()->GetBoolean( - prefs::kHotwordAudioLoggingEnabled)) { - launch_mode = HotwordService::HOTWORD_ONLY; - } - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - - if (!hotword_service) - return; - - hotword_service->LaunchHotwordAudioVerificationApp(launch_mode); - - // Close the notification after it's been clicked on to remove it - // from the notification tray. - g_browser_process->notification_ui_manager()->CancelById( - hotword_internal::kHotwordNotificationId, - NotificationUIManager::GetProfileID(profile_)); - } - - private: - ~HotwordNotificationDelegate() override {} - - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(HotwordNotificationDelegate); -}; - -// static -bool HotwordService::DoesHotwordSupportLanguage(Profile* profile) { - std::string normalized_locale = - base::ToLowerASCII(l10n_util::NormalizeLocale(GetCurrentLocale(profile))); - - // For M43, we are limiting always-on to en_us only. - // TODO(kcarattini): Remove this once - // https://code.google.com/p/chrome-os-partner/issues/detail?id=39227 - // is fixed. - if (HotwordServiceFactory::IsAlwaysOnAvailable()) - return normalized_locale == "en_us"; - - for (size_t i = 0; i < arraysize(kSupportedLocales); i++) { - if (normalized_locale == kSupportedLocales[i]) - return true; - } - return false; -} - -// static -bool HotwordService::IsHotwordHardwareAvailable() { -#if defined(OS_CHROMEOS) - if (chromeos::CrasAudioHandler::IsInitialized()) { - chromeos::AudioDeviceList devices; - chromeos::CrasAudioHandler::Get()->GetAudioDevices(&devices); - for (size_t i = 0; i < devices.size(); ++i) { - if (devices[i].type == chromeos::AUDIO_TYPE_HOTWORD) { - DCHECK(devices[i].is_input); - return true; - } - } - } -#endif - return false; -} - -#if defined(OS_CHROMEOS) -class HotwordService::HotwordUserSessionStateObserver - : public user_manager::UserManager::UserSessionStateObserver { - public: - explicit HotwordUserSessionStateObserver(HotwordService* service) - : service_(service) {} - - // Overridden from UserSessionStateObserver: - void ActiveUserChanged(const user_manager::User* active_user) override { - service_->ActiveUserChanged(); - } - - private: - HotwordService* service_; // Not owned -}; -#else -// Dummy class to please the linker. -class HotwordService::HotwordUserSessionStateObserver { -}; -#endif - -void HotwordService::HotwordWebstoreInstaller::Shutdown() { - AbortInstall(); -} - -HotwordService::HotwordService(Profile* profile) - : profile_(profile), - extension_registry_observer_(this), - microphone_available_(false), - audio_device_state_updated_(false), - client_(NULL), - error_message_(0), - reinstall_pending_(false), - training_(false), - weak_factory_(this) { - extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile)); - - // Disable the old extension so it doesn't interfere with the new stuff. - ExtensionService* extension_service = GetExtensionService(profile_); - if (extension_service) { - extension_service->DisableExtension( - kHotwordOldExtensionId, - extensions::disable_reason::DISABLE_USER_ACTION); - } - - // This will be called during profile initialization which is a good time - // to check the user's hotword state. - RecordHotwordEnabledMetric(this, profile_); - - pref_registrar_.Init(profile_->GetPrefs()); - pref_registrar_.Add( - prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&HotwordService::OnHotwordAlwaysOnSearchEnabledChanged, - base::Unretained(this))); - - extensions::ExtensionSystem::Get(profile_)->ready().Post( - FROM_HERE, - base::Bind(base::IgnoreResult( - &HotwordService::MaybeReinstallHotwordExtension), - weak_factory_.GetWeakPtr())); - -// This service is actually used only on ChromeOS, and the next function -// results in a sequence of calls that triggers -// HotwordAudioHistoryHandler::GetAudioHistoryEnabled which is not supported -// on other platforms. -#if defined(OS_CHROMEOS) - SetAudioHistoryHandler(new HotwordAudioHistoryHandler( - profile_, base::ThreadTaskRunnerHandle::Get())); -#endif - - if (HotwordServiceFactory::IsAlwaysOnAvailable() && - IsHotwordAllowed()) { - // Show the hotword notification in 5 seconds if the experimental flag is - // on, or in 10 minutes if not. We need to wait at least a few seconds - // for the hotword extension to be installed. - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware)) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordService::ShowHotwordNotification, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromSeconds(5)); - } else if (!profile_->GetPrefs()->GetBoolean( - prefs::kHotwordAlwaysOnNotificationSeen)) { - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( - FROM_HERE, - base::BindOnce(&HotwordService::ShowHotwordNotification, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMinutes(10)); - } - } - -#if defined(OS_CHROMEOS) - if (user_manager::UserManager::IsInitialized()) { - session_observer_.reset(new HotwordUserSessionStateObserver(this)); - user_manager::UserManager::Get()->AddSessionStateObserver( - session_observer_.get()); - } -#endif - - // Register with the device observer list to update the microphone - // availability. - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::BindOnce(&HotwordService::InitializeMicrophoneObserver, - weak_factory_.GetWeakPtr())); -} - -HotwordService::~HotwordService() { -#if defined(OS_CHROMEOS) - if (user_manager::UserManager::IsInitialized() && session_observer_) { - user_manager::UserManager::Get()->RemoveSessionStateObserver( - session_observer_.get()); - } -#endif -} - -void HotwordService::Shutdown() { - if (installer_.get()) - installer_->Shutdown(); -} - -void HotwordService::ShowHotwordNotification() { - // Check for enabled here in case always-on was enabled during the delay. - if (!IsServiceAvailable() || IsAlwaysOnEnabled()) - return; - - message_center::RichNotificationData data; - const base::string16 label = l10n_util::GetStringUTF16( - IDS_HOTWORD_NOTIFICATION_BUTTON); - data.buttons.push_back(message_center::ButtonInfo(label)); - - message_center::Notification notification( - message_center::NOTIFICATION_TYPE_SIMPLE, - hotword_internal::kHotwordNotificationId, - l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_TITLE), - l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_DESCRIPTION), - ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_HOTWORD_NOTIFICATION_ICON), - base::string16(), GURL(), - message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT, - hotword_internal::kHotwordNotifierId), - data, new HotwordNotificationDelegate(profile_)); - - g_browser_process->notification_ui_manager()->Add(notification, profile_); - profile_->GetPrefs()->SetBoolean( - prefs::kHotwordAlwaysOnNotificationSeen, true); -} - -void HotwordService::OnExtensionUninstalled( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UninstallReason reason) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - if (extension->id() != extension_misc::kHotwordSharedModuleId || - profile_ != Profile::FromBrowserContext(browser_context) || - !GetExtensionService(profile_)) - return; - - // If the extension wasn't uninstalled due to language change, don't try to - // reinstall it. - if (!reinstall_pending_) - return; - - InstallHotwordExtensionFromWebstore(kMaxInstallRetries); - SetPreviousLanguagePref(); -} - -std::string HotwordService::ReinstalledExtensionId() { - return extension_misc::kHotwordSharedModuleId; -} - -void HotwordService::InitializeMicrophoneObserver() { - MediaCaptureDevicesDispatcher::GetInstance()->AddObserver(this); -} - -void HotwordService::InstalledFromWebstoreCallback( - int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result) { - if (result != extensions::webstore_install::SUCCESS && num_tries) { - // Try again on failure. - content::BrowserThread::PostDelayedTask( - content::BrowserThread::UI, FROM_HERE, - base::BindOnce(&HotwordService::InstallHotwordExtensionFromWebstore, - weak_factory_.GetWeakPtr(), num_tries), - base::TimeDelta::FromSeconds(kInstallRetryDelaySeconds)); - } -} - -void HotwordService::InstallHotwordExtensionFromWebstore(int num_tries) { - installer_ = new HotwordWebstoreInstaller( - ReinstalledExtensionId(), - profile_, - base::Bind(&HotwordService::InstalledFromWebstoreCallback, - weak_factory_.GetWeakPtr(), - num_tries - 1)); - installer_->BeginInstall(); -} - -void HotwordService::OnExtensionInstalled( - content::BrowserContext* browser_context, - const extensions::Extension* extension, - bool is_update) { - - if (extension->id() != extension_misc::kHotwordSharedModuleId || - profile_ != Profile::FromBrowserContext(browser_context)) - return; - - // If the previous locale pref has never been set, set it now since - // the extension has been installed. - if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage)) - SetPreviousLanguagePref(); - - // If MaybeReinstallHotwordExtension already triggered an uninstall, we - // don't want to loop and trigger another uninstall-install cycle. - // However, if we arrived here via an uninstall-triggered-install (and in - // that case |reinstall_pending_| will be true) then we know install - // has completed and we can reset |reinstall_pending_|. - if (!reinstall_pending_) - MaybeReinstallHotwordExtension(); - else - reinstall_pending_ = false; -} - -bool HotwordService::MaybeReinstallHotwordExtension() { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - ExtensionService* extension_service = GetExtensionService(profile_); - if (!extension_service) - return false; - - const extensions::Extension* extension = extension_service->GetExtensionById( - ReinstalledExtensionId(), true); - if (!extension) - return false; - - // If the extension is currently pending, return and we'll check again - // after the install is finished. - extensions::PendingExtensionManager* pending_manager = - extension_service->pending_extension_manager(); - if (pending_manager->IsIdPending(extension->id())) - return false; - - // If there is already a pending request from HotwordService, don't try - // to uninstall either. - if (reinstall_pending_) - return false; - - // Check if the current locale matches the previous. If they don't match, - // uninstall the extension. - if (!ShouldReinstallHotwordExtension()) - return false; - - // Ensure the call to OnExtensionUninstalled was triggered by a language - // change so it's okay to reinstall. - reinstall_pending_ = true; - - // Disable always-on on a language change. We do this because the speaker-id - // model needs to be re-trained. - if (IsAlwaysOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - } - - // Record re-installs due to language change. - UMA_HISTOGRAM_SPARSE_SLOWLY( - "Hotword.SharedModuleReinstallLanguage", - language_usage_metrics::LanguageUsageMetrics::ToLanguageCode( - GetCurrentLocale(profile_))); - return UninstallHotwordExtension(extension_service); -} - -bool HotwordService::UninstallHotwordExtension( - ExtensionService* extension_service) { - base::string16 error; - std::string extension_id = ReinstalledExtensionId(); - if (!extension_service->UninstallExtension( - extension_id, - extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT, - &error)) { - LOG(WARNING) << "Cannot uninstall extension with id " - << extension_id - << ": " << error; - reinstall_pending_ = false; - return false; - } - return true; -} - -bool HotwordService::IsServiceAvailable() { - error_message_ = 0; - - // Determine if the extension is available. - extensions::ExtensionSystem* system = - extensions::ExtensionSystem::Get(profile_); - ExtensionService* service = system->extension_service(); - // Include disabled extensions (true parameter) since it may not be enabled - // if the user opted out. - const extensions::Extension* extension = - service->GetExtensionById(ReinstalledExtensionId(), true); - if (!extension) - error_message_ = IDS_HOTWORD_GENERIC_ERROR_MESSAGE; - - // TODO(amistry): Record availability of shared module in UMA. - RecordLoggingMetrics(profile_); - - // Determine if NaCl is available. - bool nacl_enabled = false; - base::FilePath path; - if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) { - content::WebPluginInfo info; - PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_).get(); - if (content::PluginService::GetInstance()->GetPluginInfoByPath(path, &info)) - nacl_enabled = plugin_prefs->IsPluginEnabled(info); - } - if (!nacl_enabled) - error_message_ = IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE; - - RecordErrorMetrics(error_message_); - - // Determine if the proper audio capabilities exist. The first time this is - // called, it probably won't return in time, but that's why it won't be - // included in the error calculation. However, this use case is rare and - // typically the devices will be initialized by the time a user goes to - // settings. - HotwordServiceFactory::GetInstance()->UpdateMicrophoneState(); - if (audio_device_state_updated_) { - bool audio_capture_allowed = - profile_->GetPrefs()->GetBoolean(prefs::kAudioCaptureAllowed); - if (!audio_capture_allowed || !microphone_available_) - error_message_ = IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE; - } - - return (error_message_ == 0) && IsHotwordAllowed(); -} - -bool HotwordService::IsHotwordAllowed() { -#if defined(ENABLE_HOTWORDING) - return DoesHotwordSupportLanguage(profile_); -#else - return false; -#endif -} - -bool HotwordService::IsOptedIntoAudioLogging() { - // Do not opt the user in if the preference has not been set. - return - profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAudioLoggingEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled); -} - -bool HotwordService::IsAlwaysOnEnabled() { - return - profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled) && - HotwordServiceFactory::IsAlwaysOnAvailable(); -} - -bool HotwordService::IsSometimesOnEnabled() { - return profile_->GetPrefs()->HasPrefPath(prefs::kHotwordSearchEnabled) && - profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled) && - !HotwordServiceFactory::IsAlwaysOnAvailable(); -} - -void HotwordService::SpeakerModelExistsComplete(bool exists) { - if (exists) { - profile_->GetPrefs()-> - SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - } else { - LaunchHotwordAudioVerificationApp(HotwordService::HOTWORD_ONLY); - } -} - -void HotwordService::OptIntoHotwording( - const LaunchMode& launch_mode) { - // If the notification is in the notification tray, remove it (since the user - // is manually opting in to hotwording, they do not need the promotion). - g_browser_process->notification_ui_manager()->CancelById( - hotword_internal::kHotwordNotificationId, - NotificationUIManager::GetProfileID(profile_)); - - // First determine if we actually need to launch the app, or can just enable - // the pref. If Audio History has already been enabled, and we already have - // a speaker model, then we don't need to launch the app at all. - if (launch_mode == HotwordService::HOTWORD_ONLY) { - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get( - profile_); - if (event_service) { - event_service->OnSpeakerModelExists(); - return; - } - } - - LaunchHotwordAudioVerificationApp(launch_mode); -} - -void HotwordService::LaunchHotwordAudioVerificationApp( - const LaunchMode& launch_mode) { - hotword_audio_verification_launch_mode_ = launch_mode; - - ExtensionService* extension_service = GetExtensionService(profile_); - if (!extension_service) - return; - const extensions::Extension* extension = extension_service->GetExtensionById( - extension_misc::kHotwordAudioVerificationAppId, true); - if (!extension) - return; - - OpenApplication(AppLaunchParams( - profile_, extension, extensions::LAUNCH_CONTAINER_WINDOW, - WindowOpenDisposition::NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL)); -} - -HotwordService::LaunchMode -HotwordService::GetHotwordAudioVerificationLaunchMode() { - return hotword_audio_verification_launch_mode_; -} - -void HotwordService::StartTraining() { - training_ = true; - - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled); -} - -void HotwordService::FinalizeSpeakerModel() { - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnFinalizeSpeakerModel(); -} - -void HotwordService::StopTraining() { - training_ = false; - - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled); -} - -void HotwordService::NotifyHotwordTriggered() { - if (!IsServiceAvailable()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnHotwordTriggered(); -} - -bool HotwordService::IsTraining() { - return training_; -} - -HotwordAudioHistoryHandler* HotwordService::GetAudioHistoryHandler() { - return audio_history_handler_.get(); -} - -void HotwordService::SetAudioHistoryHandler( - HotwordAudioHistoryHandler* handler) { - audio_history_handler_.reset(handler); - audio_history_handler_->UpdateAudioHistoryState(); -} - -void HotwordService::DisableHotwordPreferences() { - if (IsSometimesOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false); - } - if (IsAlwaysOnEnabled()) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - } -} - -void HotwordService::OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) { - bool microphone_was_available = microphone_available_; - microphone_available_ = !devices.empty(); - audio_device_state_updated_ = true; - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service && microphone_was_available != microphone_available_) - event_service->OnMicrophoneStateChanged(microphone_available_); -} - -void HotwordService::OnHotwordAlwaysOnSearchEnabledChanged( - const std::string& pref_name) { - // If the pref for always on has been changed in some way, that means that - // the user is aware of always on (either from settings or another source) - // so they don't need to be shown the notification. - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnNotificationSeen, - true); - pref_registrar_.Remove(prefs::kHotwordAlwaysOnSearchEnabled); -} - -void HotwordService::RequestHotwordSession(HotwordClient* client) { - if (!IsServiceAvailable() || (client_ && client_ != client)) - return; - - client_ = client; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnHotwordSessionRequested(); -} - -void HotwordService::StopHotwordSession(HotwordClient* client) { - if (!IsServiceAvailable()) - return; - - // Do nothing if there's no client. - if (!client_) - return; - DCHECK(client_ == client); - - client_ = NULL; - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - if (event_service) - event_service->OnHotwordSessionStopped(); -} - -void HotwordService::SetPreviousLanguagePref() { - profile_->GetPrefs()->SetString(prefs::kHotwordPreviousLanguage, - GetCurrentLocale(profile_)); -} - -bool HotwordService::ShouldReinstallHotwordExtension() { - // If there is no previous locale pref, then this is the first install - // so no need to uninstall first. - if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage)) - return false; - - std::string previous_locale = - profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage); - std::string locale = GetCurrentLocale(profile_); - - // If it's a new locale, then the old extension should be uninstalled. - return locale != previous_locale && - HotwordService::DoesHotwordSupportLanguage(profile_); -} - -void HotwordService::ActiveUserChanged() { - // Don't bother notifying the extension if hotwording is completely off. - if (!IsSometimesOnEnabled() && !IsAlwaysOnEnabled() && !IsTraining()) - return; - - HotwordPrivateEventService* event_service = - BrowserContextKeyedAPIFactory::Get(profile_); - // "enabled" isn't being changed, but piggy-back off the notification anyway. - if (event_service) - event_service->OnEnabledChanged(prefs::kHotwordSearchEnabled); -} - -bool HotwordService::UserIsActive() { -#if defined(OS_CHROMEOS) - // Only support multiple profiles and profile switching in ChromeOS. - if (user_manager::UserManager::IsInitialized()) { - user_manager::User* user = - user_manager::UserManager::Get()->GetActiveUser(); - if (user && user->is_profile_created()) - return profile_ == ProfileManager::GetActiveUserProfile(); - } -#endif - return true; -} diff --git a/chrome/browser/search/hotword_service.h b/chrome/browser/search/hotword_service.h deleted file mode 100644 index 46f1e152dacf4..0000000000000 --- a/chrome/browser/search/hotword_service.h +++ /dev/null @@ -1,244 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_ - -#include - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/scoped_observer.h" -#include "chrome/browser/extensions/webstore_startup_installer.h" -#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" -#include "chrome/common/extensions/webstore_install_result.h" -#include "components/keyed_service/core/keyed_service.h" -#include "components/prefs/pref_change_registrar.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" -#include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_registry_observer.h" - -class ExtensionService; -class HotwordAudioHistoryHandler; -class HotwordClient; -class Profile; - -namespace extensions { -class Extension; -} // namespace extensions - -namespace hotword_internal { -// String passed to indicate the training state has changed. -extern const char kHotwordTrainingEnabled[]; -} // namespace hotword_internal - -// Provides an interface for the Hotword component that does voice triggered -// search. -class HotwordService : public MediaCaptureDevicesDispatcher::Observer, - public extensions::ExtensionRegistryObserver, - public KeyedService { - public: - // A simple subclass to allow for aborting an install during shutdown. - // HotwordWebstoreInstaller class is public for testing. - class HotwordWebstoreInstaller : public extensions::WebstoreStartupInstaller { - public: - HotwordWebstoreInstaller(const std::string& webstore_item_id, - Profile* profile, - const Callback& callback) - : extensions::WebstoreStartupInstaller(webstore_item_id, - profile, - false, - callback) {} - void Shutdown(); - protected: - ~HotwordWebstoreInstaller() override {} - }; - - // Returns true if the hotword supports the current system language. - static bool DoesHotwordSupportLanguage(Profile* profile); - - // Returns true if hotwording hardware is available. - static bool IsHotwordHardwareAvailable(); - - explicit HotwordService(Profile* profile); - ~HotwordService() override; - - // Overridden from ExtensionRegisterObserver: - void OnExtensionInstalled(content::BrowserContext* browser_context, - const extensions::Extension* extension, - bool is_update) override; - void OnExtensionUninstalled(content::BrowserContext* browser_context, - const extensions::Extension* extension, - extensions::UninstallReason reason) override; - - // Overriden from KeyedService - void Shutdown() override; - - // Checks for whether all the necessary files have downloaded to allow for - // using the extension. - virtual bool IsServiceAvailable(); - - // Determine if hotwording is allowed in this profile based on field trials - // and language. - virtual bool IsHotwordAllowed(); - - // Checks if the user has opted into audio logging. Returns true if the user - // is opted in, false otherwise.. - bool IsOptedIntoAudioLogging(); - - // Returns whether always-on hotwording is enabled. - bool IsAlwaysOnEnabled(); - - // Returns whether google.com/NTP/launcher hotwording is enabled. - bool IsSometimesOnEnabled(); - - // Handles enabling/disabling the hotword notification when the user - // changes the always on search settings. - void OnHotwordAlwaysOnSearchEnabledChanged(const std::string& pref_name); - - // Called to handle the hotword session from |client|. - void RequestHotwordSession(HotwordClient* client); - void StopHotwordSession(HotwordClient* client); - HotwordClient* client() { return client_; } - - // Checks if the current version of the hotword extension should be - // uninstalled in order to update to a different language version. - // Returns true if the extension was uninstalled. - bool MaybeReinstallHotwordExtension(); - - // Checks based on locale if the current version should be uninstalled so that - // a version with a different language can be installed. - bool ShouldReinstallHotwordExtension(); - - // Helper functions pulled out for testing purposes. - // UninstallHotwordExtension returns true if the extension was uninstalled. - virtual bool UninstallHotwordExtension(ExtensionService* extension_service); - virtual void InstallHotwordExtensionFromWebstore(int num_tries); - - // Sets the pref value of the previous language. - void SetPreviousLanguagePref(); - - // Returns the current error message id. A value of 0 indicates - // no error. - int error_message() { return error_message_; } - - bool microphone_available() { return microphone_available_; } - - // These methods are for launching, and getting and setting the launch mode of - // the Hotword Audio Verification App. - // - // OptIntoHotwording first determines if the app needs to be launched, and if - // so, launches the app (if Audio History is on and a speaker model exists, - // then we don't need to launch the app). - // - // LaunchHotwordAudioVerificationApp launches the app without the above - // check in the specified |launch_mode|. - enum LaunchMode { - HOTWORD_ONLY, - HOTWORD_AND_AUDIO_HISTORY, - RETRAIN - }; - void OptIntoHotwording(const LaunchMode& launch_mode); - void LaunchHotwordAudioVerificationApp(const LaunchMode& launch_mode); - virtual LaunchMode GetHotwordAudioVerificationLaunchMode(); - - // Called when the SpeakerModelExists request is complete. Either - // sets the always-on hotword pref to true, or launches the Hotword - // Audio Verification App, depending on the value of |exists|. - void SpeakerModelExistsComplete(bool exists); - - // These methods control the speaker training communication between - // the Hotword Audio Verification App and the Hotword Extension that - // contains the NaCl module. - void StartTraining(); - void FinalizeSpeakerModel(); - void StopTraining(); - void NotifyHotwordTriggered(); - - // Returns true if speaker training is currently in progress. - bool IsTraining(); - - // Indicate that the currently active user has changed. - void ActiveUserChanged(); - - // Return true if this profile corresponds to the currently active user. - bool UserIsActive(); - - // Returns a pointer to the audio history handler. - HotwordAudioHistoryHandler* GetAudioHistoryHandler(); - - // Sets the audio history handler. Used for tests. - void SetAudioHistoryHandler(HotwordAudioHistoryHandler* handler); - - // Turn off the currently enabled version of hotwording if one exists. - void DisableHotwordPreferences(); - - // Overridden from MediaCaptureDevicesDispatcher::Observer - void OnUpdateAudioDevices( - const content::MediaStreamDevices& devices) override; - - protected: - // Used in test subclasses. - scoped_refptr installer_; - - private: - class HotwordUserSessionStateObserver; - - // Must be called from the UI thread since the instance of - // MediaCaptureDevicesDispatcher can only be accessed on the UI thread. - void InitializeMicrophoneObserver(); - - // Callback for webstore extension installer. - void InstalledFromWebstoreCallback( - int num_tries, - bool success, - const std::string& error, - extensions::webstore_install::Result result); - - // Returns the ID of the extension that may need to be reinstalled. - std::string ReinstalledExtensionId(); - - // Creates a notification for always-on hotwording. - void ShowHotwordNotification(); - - Profile* profile_; - - PrefChangeRegistrar pref_registrar_; - - content::NotificationRegistrar registrar_; - - // For observing the ExtensionRegistry. - ScopedObserver - extension_registry_observer_; - - std::unique_ptr audio_history_handler_; - - bool microphone_available_; - - // Indicates if the check for audio devices has been run such that it can be - // included in the error checking. Audio checking is not done immediately - // upon start up because of the negative impact on performance. - bool audio_device_state_updated_; - - HotwordClient* client_; - int error_message_; - bool reinstall_pending_; - // Whether we are currently in the process of training the speaker model. - bool training_; - std::unique_ptr session_observer_; - - // Stores the launch mode for the Hotword Audio Verification App. - LaunchMode hotword_audio_verification_launch_mode_; - - // The WeakPtrFactory should be the last member, so the weak pointer - // gets invalidated before the destructors for other members run, - // to avoid callbacks into a half-destroyed object. - base::WeakPtrFactory weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(HotwordService); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_H_ diff --git a/chrome/browser/search/hotword_service_factory.cc b/chrome/browser/search/hotword_service_factory.cc deleted file mode 100644 index d18b14c2cb9cf..0000000000000 --- a/chrome/browser/search/hotword_service_factory.cc +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service_factory.h" - -#include "base/command_line.h" -#include "build/build_config.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/browser_thread.h" - -using content::BrowserContext; -using content::BrowserThread; - -// static -HotwordService* HotwordServiceFactory::GetForProfile(BrowserContext* context) { - return static_cast( - GetInstance()->GetServiceForBrowserContext(context, true)); -} - -// static -HotwordServiceFactory* HotwordServiceFactory::GetInstance() { - return base::Singleton::get(); -} - -// static -bool HotwordServiceFactory::IsServiceAvailable(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - return hotword_service && hotword_service->IsServiceAvailable(); -} - -// static -bool HotwordServiceFactory::IsHotwordAllowed(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - return hotword_service && hotword_service->IsHotwordAllowed(); -} - -// static -bool HotwordServiceFactory::IsAlwaysOnAvailable() { -#if defined(OS_CHROMEOS) - if (HotwordService::IsHotwordHardwareAvailable()) - return true; -#endif - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - return command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware); -} - -// static -int HotwordServiceFactory::GetCurrentError(BrowserContext* context) { - HotwordService* hotword_service = GetForProfile(context); - if (!hotword_service) - return 0; - return hotword_service->error_message(); -} - -HotwordServiceFactory::HotwordServiceFactory() - : BrowserContextKeyedServiceFactory( - "HotwordService", - BrowserContextDependencyManager::GetInstance()) { - // No dependencies. -} - -HotwordServiceFactory::~HotwordServiceFactory() { -} - -void HotwordServiceFactory::UpdateMicrophoneState() { - // In order to trigger the monitor, just call getAudioCaptureDevices. - content::MediaStreamDevices devices = - MediaCaptureDevicesDispatcher::GetInstance()->GetAudioCaptureDevices(); -} - -void HotwordServiceFactory::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* prefs) { - prefs->RegisterBooleanPref(prefs::kHotwordAudioLoggingEnabled, - false, - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - prefs->RegisterStringPref(prefs::kHotwordPreviousLanguage, - std::string(), - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - // Per-device settings (do not sync). - prefs->RegisterBooleanPref(prefs::kHotwordSearchEnabled, false); - prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnSearchEnabled, false); - prefs->RegisterBooleanPref(prefs::kHotwordAlwaysOnNotificationSeen, false); -} - -KeyedService* HotwordServiceFactory::BuildServiceInstanceFor( - BrowserContext* context) const { - return new HotwordService(Profile::FromBrowserContext(context)); -} diff --git a/chrome/browser/search/hotword_service_factory.h b/chrome/browser/search/hotword_service_factory.h deleted file mode 100644 index 050872c1b7a8d..0000000000000 --- a/chrome/browser/search/hotword_service_factory.h +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_ -#define CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_ - -#include "base/macros.h" -#include "base/memory/singleton.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class HotwordService; - -// Singleton that owns all HotwordServices and associates them with Profiles. -class HotwordServiceFactory : public BrowserContextKeyedServiceFactory { - public: - // Returns the HotwordService for |context|. - static HotwordService* GetForProfile(content::BrowserContext* context); - - static HotwordServiceFactory* GetInstance(); - - // Returns true if the hotwording service is available for |context|. - static bool IsServiceAvailable(content::BrowserContext* context); - - // Returns true if hotwording is allowed for |context|. - static bool IsHotwordAllowed(content::BrowserContext* context); - - // Returns whether always-on hotwording is available. - static bool IsAlwaysOnAvailable(); - - // Returns the current error message for the service for |context|. - // A value of 0 indicates no error. - static int GetCurrentError(content::BrowserContext* context); - - // This will kick off the monitor that calls OnUpdateAudioDevices when the - // number of audio devices changes (or is initialized). It needs to be a - // separate function so it can be called after the service is initialized - // (i.e., after startup). The monitor can't be initialized during startup - // because it would slow down startup too much so it is delayed and not - // called until it's needed by the webui in browser_options_handler. - void UpdateMicrophoneState(); - - private: - friend struct base::DefaultSingletonTraits; - - HotwordServiceFactory(); - ~HotwordServiceFactory() override; - - // Overrides from BrowserContextKeyedServiceFactory: - void RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* context) const override; - - DISALLOW_COPY_AND_ASSIGN(HotwordServiceFactory); -}; - -#endif // CHROME_BROWSER_SEARCH_HOTWORD_SERVICE_FACTORY_H_ diff --git a/chrome/browser/search/hotword_service_unittest.cc b/chrome/browser/search/hotword_service_unittest.cc deleted file mode 100644 index e0eb877f234ce..0000000000000 --- a/chrome/browser/search/hotword_service_unittest.cc +++ /dev/null @@ -1,534 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search/hotword_service.h" - -#include -#include - -#include "base/command_line.h" -#include "base/memory/ptr_util.h" -#include "base/metrics/field_trial.h" -#include "base/run_loop.h" -#include "base/test/test_simple_task_runner.h" -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/extensions/extension_service_test_base.h" -#include "chrome/browser/extensions/test_extension_service.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/base/testing_profile.h" -#include "components/history/core/browser/web_history_service.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/common/extension_builder.h" -#include "extensions/common/manifest.h" -#include "extensions/common/one_shot_event.h" -#include "testing/gtest/include/gtest/gtest.h" - -#if defined(OS_CHROMEOS) -#include "chromeos/audio/cras_audio_handler.h" -#endif - -namespace { - -class MockAudioHistoryHandler : public HotwordAudioHistoryHandler { - public: - MockAudioHistoryHandler( - content::BrowserContext* context, - const scoped_refptr& task_runner, - history::WebHistoryService* web_history) - : HotwordAudioHistoryHandler(context, task_runner), - get_audio_history_calls_(0), - web_history_(web_history) { - } - ~MockAudioHistoryHandler() override {} - - void GetAudioHistoryEnabled( - const HotwordAudioHistoryCallback& callback) override { - get_audio_history_calls_++; - callback.Run(true, true); - } - - history::WebHistoryService* GetWebHistory() override { - return web_history_.get(); - } - - int GetAudioHistoryCalls() { - return get_audio_history_calls_; - } - - private: - int get_audio_history_calls_; - std::unique_ptr web_history_; -}; - -class MockHotwordService : public HotwordService { - public: - explicit MockHotwordService(Profile* profile) - : HotwordService(profile), - uninstall_count_(0) { - } - - bool UninstallHotwordExtension(ExtensionService* extension_service) override { - uninstall_count_++; - return HotwordService::UninstallHotwordExtension(extension_service); - } - - void InstallHotwordExtensionFromWebstore(int num_tries) override { - std::unique_ptr manifest = - extensions::DictionaryBuilder() - .Set("name", "Hotword Test Extension") - .Set("version", "1.0") - .Set("manifest_version", 2) - .Build(); - scoped_refptr extension = - extensions::ExtensionBuilder() - .SetManifest(std::move(manifest)) - .AddFlags(extensions::Extension::FROM_WEBSTORE | - extensions::Extension::WAS_INSTALLED_BY_DEFAULT) - .SetID(extension_id_) - .SetLocation(extensions::Manifest::EXTERNAL_COMPONENT) - .Build(); - ASSERT_TRUE(extension.get()); - service_->OnExtensionInstalled(extension.get(), syncer::StringOrdinal()); - } - - - int uninstall_count() { return uninstall_count_; } - - void SetExtensionService(ExtensionService* service) { service_ = service; } - void SetExtensionId(const std::string& extension_id) { - extension_id_ = extension_id; - } - - ExtensionService* extension_service() { return service_; } - - private: - ExtensionService* service_; - int uninstall_count_; - std::string extension_id_; -}; - -std::unique_ptr BuildMockHotwordService( - content::BrowserContext* context) { - return base::MakeUnique(static_cast(context)); -} - -} // namespace - -class HotwordServiceTest : - public extensions::ExtensionServiceTestBase, - public ::testing::WithParamInterface { - protected: - HotwordServiceTest() {} - virtual ~HotwordServiceTest() {} - - void SetApplicationLocale(Profile* profile, const std::string& new_locale) { -#if defined(OS_CHROMEOS) - // On ChromeOS locale is per-profile. - profile->GetPrefs()->SetString(prefs::kApplicationLocale, new_locale); -#else - g_browser_process->SetApplicationLocale(new_locale); -#endif - } - - void SetUp() override { - extension_id_ = GetParam(); -#if defined(OS_CHROMEOS) - // Tests on chromeos need to have the handler initialized. - chromeos::CrasAudioHandler::InitializeForTesting(); -#endif - - extensions::ExtensionServiceTestBase::SetUp(); - } - - void TearDown() override { -#if defined(OS_CHROMEOS) - DCHECK(chromeos::CrasAudioHandler::IsInitialized()); - chromeos::CrasAudioHandler::Shutdown(); -#endif - } - - std::string extension_id_; -}; - -INSTANTIATE_TEST_CASE_P(HotwordServiceTests, - HotwordServiceTest, - ::testing::Values( - extension_misc::kHotwordSharedModuleId)); - -// Disabled due to http://crbug.com/503963. -TEST_P(HotwordServiceTest, DISABLED_IsHotwordAllowedLocale) { - TestingProfile::Builder profile_builder; - std::unique_ptr profile = profile_builder.Build(); - -#if defined(ENABLE_HOTWORDING) - bool hotwording_enabled = true; -#else - bool hotwording_enabled = false; -#endif - - // Check that the service exists so that a NULL service be ruled out in - // following tests. - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile.get()); - EXPECT_TRUE(hotword_service != NULL); - - // Set the language to an invalid one. - SetApplicationLocale(static_cast(profile.get()), "non-valid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile.get())); - - // Now with valid locales it should be fine. - SetApplicationLocale(static_cast(profile.get()), "en"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast(profile.get()), "en-US"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast(profile.get()), "en_us"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast(profile.get()), "de_DE"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - SetApplicationLocale(static_cast(profile.get()), "fr_fr"); - EXPECT_EQ(hotwording_enabled, - HotwordServiceFactory::IsHotwordAllowed(profile.get())); - - // Test that incognito even with a valid locale and valid field trial - // still returns false. - Profile* otr_profile = profile->GetOffTheRecordProfile(); - SetApplicationLocale(otr_profile, "en"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(otr_profile)); -} - -TEST_P(HotwordServiceTest, ShouldReinstallExtension) { - InitializeEmptyExtensionService(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionId(extension_id_); - - // If no locale has been set, no reason to uninstall. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "en"); - hotword_service->SetPreviousLanguagePref(); - - // Now a locale is set, but it hasn't changed. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "fr_fr"); - - // Now it's a different locale so it should uninstall. - EXPECT_TRUE(hotword_service->ShouldReinstallHotwordExtension()); -} - -TEST_P(HotwordServiceTest, PreviousLanguageSetOnInstall) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // If no locale has been set, no reason to uninstall. - EXPECT_FALSE(hotword_service->ShouldReinstallHotwordExtension()); - - SetApplicationLocale(profile(), "test_locale"); - - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ("test_locale", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); -} - -TEST_P(HotwordServiceTest, UninstallReinstallTriggeredCorrectly) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // Initialize the locale to "en". - SetApplicationLocale(profile(), "en"); - - // The previous locale should not be set. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - - // Do an initial installation. - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - EXPECT_EQ("en", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - if (extension_id_ == extension_misc::kHotwordSharedModuleId) { - // Shared module is installed and enabled. - EXPECT_EQ(0U, registry()->disabled_extensions().size()); - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id_)); - } else { - // Verify the extension is installed but disabled. - EXPECT_EQ(1U, registry()->disabled_extensions().size()); - EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id_)); - } - - // The previous locale should be set but should match the current - // locale. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - - // Switch the locale to a valid but different one. - SetApplicationLocale(profile(), "fr_fr"); -#if defined(ENABLE_HOTWORDING) - EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#else - // Disabled due to http://crbug.com/503963. - // EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#endif - - // Different but valid locale so expect uninstall. - EXPECT_TRUE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ(1, hotword_service->uninstall_count()); - EXPECT_EQ("fr_fr", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - if (extension_id_ == extension_misc::kHotwordSharedModuleId) { - // Shared module is installed and enabled. - EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id_)); - } else { - // Verify the extension is installed. It's still disabled. - EXPECT_TRUE(registry()->disabled_extensions().Contains(extension_id_)); - } - - // Switch the locale to an invalid one. - SetApplicationLocale(profile(), "invalid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ("fr_fr", - profile()->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - // If the locale is set back to the last valid one, then an uninstall-install - // shouldn't be needed. - SetApplicationLocale(profile(), "fr_fr"); -#if defined(ENABLE_HOTWORDING) - EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#else - // Disabled due to http://crbug.com/503963. - // EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); -#endif - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_EQ(1, hotword_service->uninstall_count()); // no change -} - -TEST_P(HotwordServiceTest, DisableAlwaysOnOnLanguageChange) { - // Bypass test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - // Turn on Always On - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - InitializeEmptyExtensionService(); - service_->Init(); - - // Enable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // Initialize the locale to "en_us". - SetApplicationLocale(profile(), "en_us"); - - // The previous locale should not be set. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // Do an initial installation. - hotword_service->InstallHotwordExtensionFromWebstore(1); - base::RunLoop().RunUntilIdle(); - - // The previous locale should be set but should match the current - // locale. No reason to uninstall. - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // TODO(kcarattini): Uncomment this sectione once we launch always-on - // in more languages. - // // Switch the locale to a valid but different one. - // SetApplicationLocale(profile(), "fr_fr"); - // EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); - - // // Different but valid locale so expect uninstall. - // EXPECT_TRUE(hotword_service->MaybeReinstallHotwordExtension()); - // EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Re-enable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - - // Switch the locale to an invalid one. - SetApplicationLocale(profile(), "invalid"); - EXPECT_FALSE(HotwordServiceFactory::IsHotwordAllowed(profile())); - EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // TODO(kcarattini): Uncomment this sectione once we launch always-on - // in more languages. - // // If the locale is set back to the last valid one, then an - // // uninstall-install shouldn't be needed. - // SetApplicationLocale(profile(), "fr_fr"); - // EXPECT_TRUE(HotwordServiceFactory::IsHotwordAllowed(profile())); - // EXPECT_FALSE(hotword_service->MaybeReinstallHotwordExtension()); - // EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); -} - -TEST_P(HotwordServiceTest, IsAlwaysOnEnabled) { - // Bypass test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - InitializeEmptyExtensionService(); - service_->Init(); - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // No hardware available. Should never be true. - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Enable always-on, still not available. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Enable regular hotwording, still not available. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); - - // Bypass hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - EXPECT_TRUE(hotword_service->IsAlwaysOnEnabled()); - - // Disable. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - EXPECT_FALSE(hotword_service->IsAlwaysOnEnabled()); -} - -TEST_P(HotwordServiceTest, IsSometimesOnEnabled) { - InitializeEmptyExtensionService(); - service_->Init(); - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - // No pref set. - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Set pref. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_TRUE(hotword_service->IsSometimesOnEnabled()); - - // Turn on always-on pref. Should have no effect. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true); - EXPECT_TRUE(hotword_service->IsSometimesOnEnabled()); - - // Disable. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Bypass rest of test for old hotwording. - if (extension_id_ != extension_misc::kHotwordSharedModuleId) - return; - - // Bypass hardware check. - base::CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableExperimentalHotwordHardware); - - // With hardware, only always-on is allowed. - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Set pref. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, true); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); - - // Disable always-on. - profile()->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - EXPECT_FALSE(hotword_service->IsSometimesOnEnabled()); -} - -TEST_P(HotwordServiceTest, AudioHistorySyncOccurs) { - InitializeEmptyExtensionService(); - service_->Init(); - - HotwordServiceFactory* hotword_service_factory = - HotwordServiceFactory::GetInstance(); - - MockHotwordService* hotword_service = static_cast( - hotword_service_factory->SetTestingFactoryAndUse( - profile(), BuildMockHotwordService)); - ASSERT_TRUE(hotword_service != NULL); - hotword_service->SetExtensionService(service()); - hotword_service->SetExtensionId(extension_id_); - - scoped_refptr test_task_runner( - new base::TestSimpleTaskRunner()); - MockAudioHistoryHandler* audio_history_handler = - new MockAudioHistoryHandler(profile(), test_task_runner, nullptr); - hotword_service->SetAudioHistoryHandler(audio_history_handler); - EXPECT_EQ(1, audio_history_handler->GetAudioHistoryCalls()); - // We expect the next check for audio history to be in the queue. - EXPECT_EQ(base::TimeDelta::FromDays(1), - test_task_runner->NextPendingTaskDelay()); - EXPECT_TRUE(test_task_runner->HasPendingTask()); - test_task_runner->RunPendingTasks(); - EXPECT_EQ(2, audio_history_handler->GetAudioHistoryCalls()); - EXPECT_TRUE(test_task_runner->HasPendingTask()); - test_task_runner->ClearPendingTasks(); -} diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index a3a0dc28bfaea..c70eec8f40f47 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn @@ -1465,8 +1465,6 @@ split_static_library("ui") { "webui/chromeos/system_web_dialog_delegate.h", "webui/chromeos/user_image_source.cc", "webui/chromeos/user_image_source.h", - "webui/chromeos/voice_search_ui.cc", - "webui/chromeos/voice_search_ui.h", "webui/extensions/chromeos/kiosk_apps_handler.cc", "webui/extensions/chromeos/kiosk_apps_handler.h", "webui/help/help_utils_chromeos.cc", diff --git a/chrome/browser/ui/app_list/search/search_resource_manager.cc b/chrome/browser/ui/app_list/search/search_resource_manager.cc index 011b1708cd286..d59688600f6cc 100644 --- a/chrome/browser/ui/app_list/search/search_resource_manager.cc +++ b/chrome/browser/ui/app_list/search/search_resource_manager.cc @@ -4,6 +4,8 @@ #include "chrome/browser/ui/app_list/search/search_resource_manager.h" +#include + #include "ash/app_list/model/search_box_model.h" #include "base/memory/ptr_util.h" #include "chrome/browser/ui/app_list/start_page_service.h" @@ -20,16 +22,10 @@ namespace { std::unique_ptr CreateNewProperty( SpeechRecognitionState state) { - if (state == SPEECH_RECOGNITION_OFF) - return nullptr; - - ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); - return base::MakeUnique( - *bundle.GetImageSkiaNamed(IDR_APP_LIST_MIC_HOTWORD_ON), - l10n_util::GetStringUTF16(IDS_APP_LIST_HOTWORD_LISTENING), - *bundle.GetImageSkiaNamed(IDR_APP_LIST_MIC_HOTWORD_OFF), - l10n_util::GetStringUTF16(IDS_APP_LIST_START_SPEECH_RECOGNITION), - l10n_util::GetStringUTF16(IDS_TOOLTIP_MIC_SEARCH)); + // Currently no speech support in app list. + // TODO(xiaohuic): when implementing speech support in new app list, we should + // either reuse this and related logic or delete them. + return nullptr; } } // namespace @@ -58,10 +54,7 @@ void SearchResourceManager::OnSpeechRecognitionStateChanged( search_box_->SetHintText( l10n_util::GetStringUTF16(IDS_SEARCH_BOX_HINT_FULLSCREEN)); } else { - search_box_->SetHintText(l10n_util::GetStringUTF16( - (new_state == SPEECH_RECOGNITION_HOTWORD_LISTENING) - ? IDS_SEARCH_BOX_HOTWORD_HINT - : IDS_SEARCH_BOX_HINT)); + search_box_->SetHintText(l10n_util::GetStringUTF16(IDS_SEARCH_BOX_HINT)); search_box_->SetSpeechRecognitionButton(CreateNewProperty(new_state)); } } diff --git a/chrome/browser/ui/app_list/start_page_service.cc b/chrome/browser/ui/app_list/start_page_service.cc index c92b54a85afbd..51f5d1bf2bceb 100644 --- a/chrome/browser/ui/app_list/start_page_service.cc +++ b/chrome/browser/ui/app_list/start_page_service.cc @@ -21,8 +21,6 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/media/webrtc/media_stream_devices_controller.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/browser/ui/app_list/speech_auth_helper.h" @@ -228,8 +226,6 @@ class StartPageService::AudioStatus private: void CheckAndUpdate() { - // TODO(mukai): If the system can listen, this should also restart the - // hotword recognition. start_page_service_->OnMicrophoneChanged(CanListen()); } @@ -424,14 +420,6 @@ void StartPageService::StopSpeechRecognition() { OnSpeechRecognitionStateChanged(SPEECH_RECOGNITION_READY); } -bool StartPageService::HotwordEnabled() { - HotwordService* service = HotwordServiceFactory::GetForProfile(profile_); - return state_ != SPEECH_RECOGNITION_OFF && - service && - (service->IsSometimesOnEnabled() || service->IsAlwaysOnEnabled()) && - service->IsServiceAvailable(); -} - content::WebContents* StartPageService::GetStartPageContents() { return contents_.get(); } @@ -481,12 +469,7 @@ void StartPageService::OnSpeechRecognitionStateChanged( } if (!InSpeechRecognition(state_) && InSpeechRecognition(new_state)) { - if (!speech_button_toggled_manually_ && - state_ == SPEECH_RECOGNITION_HOTWORD_LISTENING) { - RecordAction(UserMetricsAction("AppList_HotwordRecognized")); - } else { RecordAction(UserMetricsAction("AppList_VoiceSearchStartedManually")); - } } else if (InSpeechRecognition(state_) && !InSpeechRecognition(new_state) && !speech_result_obtained_) { RecordAction(UserMetricsAction("AppList_VoiceSearchCanceled")); @@ -498,18 +481,6 @@ void StartPageService::OnSpeechRecognitionStateChanged( observer.OnSpeechRecognitionStateChanged(new_state); } -void StartPageService::GetSpeechAuthParameters(std::string* auth_scope, - std::string* auth_token) { - HotwordService* service = HotwordServiceFactory::GetForProfile(profile_); - if (service && - service->IsOptedIntoAudioLogging() && - service->IsAlwaysOnEnabled() && - !speech_auth_helper_->GetToken().empty()) { - *auth_scope = speech_auth_helper_->GetScope(); - *auth_token = speech_auth_helper_->GetToken(); - } -} - void StartPageService::Shutdown() { UnloadContents(); audio_status_.reset(); diff --git a/chrome/browser/ui/app_list/start_page_service.h b/chrome/browser/ui/app_list/start_page_service.h index 1c325706f977a..184c43bfa1200 100644 --- a/chrome/browser/ui/app_list/start_page_service.h +++ b/chrome/browser/ui/app_list/start_page_service.h @@ -77,9 +77,6 @@ class StartPageService : public KeyedService, // Called when the WebUI has finished loading. void WebUILoaded(); - // Returns true if the hotword is enabled in the app-launcher. - bool HotwordEnabled(); - // They return essentially the same web contents but might return NULL when // some flag disables the feature. content::WebContents* GetStartPageContents(); @@ -97,7 +94,7 @@ class StartPageService : public KeyedService, void OnSpeechRecognitionStateChanged( SpeechRecognitionState new_state) override; void GetSpeechAuthParameters(std::string* auth_scope, - std::string* auth_token) override; + std::string* auth_token) override {} protected: // Protected for testing. diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 7074c457a8b36..4077120c6cf2a 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc @@ -676,9 +676,6 @@ bool IsURLAllowedInIncognito(const GURL& url, url.host_piece() == chrome::kChromeUIThumbnailHost2 || url.host_piece() == chrome::kChromeUIThumbnailListHost || url.host_piece() == chrome::kChromeUISuggestionsHost || -#if defined(OS_CHROMEOS) - url.host_piece() == chrome::kChromeUIVoiceSearchHost || -#endif url.host_piece() == chrome::kChromeUIDevicesHost)) { return false; } diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 1b8b6f48599ff..04b9a29e1f442 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc @@ -149,7 +149,6 @@ #include "chrome/browser/ui/webui/chromeos/slow_trace_ui.h" #include "chrome/browser/ui/webui/chromeos/slow_ui.h" #include "chrome/browser/ui/webui/chromeos/sys_internals/sys_internals_ui.h" -#include "chrome/browser/ui/webui/chromeos/voice_search_ui.h" #include "components/proximity_auth/webui/proximity_auth_ui.h" #include "components/proximity_auth/webui/url_constants.h" #endif @@ -469,8 +468,6 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host_piece() == chrome::kChromeUISysInternalsHost && SysInternalsUI::IsEnabled()) return &NewWebUI; - if (url.host_piece() == chrome::kChromeUIVoiceSearchHost) - return &NewWebUI; #if !defined(OFFICIAL_BUILD) if (!base::SysInfo::IsRunningOnChromeOS()) { if (url.host_piece() == chrome::kChromeUIDeviceEmulatorHost) diff --git a/chrome/browser/ui/webui/chromeos/voice_search_ui.cc b/chrome/browser/ui/webui/chromeos/voice_search_ui.cc deleted file mode 100644 index 8b6321cdc6dd9..0000000000000 --- a/chrome/browser/ui/webui/chromeos/voice_search_ui.cc +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/chromeos/voice_search_ui.h" - -#include -#include -#include - -#include "base/files/file_enumerator.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "base/path_service.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/task_scheduler/post_task.h" -#include "base/threading/thread_restrictions.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/plugins/plugin_prefs.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" -#include "chrome/browser/ui/app_list/start_page_service.h" -#include "chrome/browser/ui/webui/version_handler.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/chrome_content_client.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/features.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/browser_resources.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/prefs/pref_service.h" -#include "components/strings/grit/components_strings.h" -#include "components/version_info/version_info.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/plugin_service.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "content/public/browser/web_ui_message_handler.h" -#include "content/public/common/user_agent.h" -#include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" -#include "extensions/common/extension.h" -#include "extensions/features/features.h" -#include "ui/base/l10n/l10n_util.h" - -using base::ASCIIToUTF16; -using content::WebUIMessageHandler; - -namespace { - -content::WebUIDataSource* CreateVoiceSearchUiHtmlSource() { - content::WebUIDataSource* html_source = - content::WebUIDataSource::Create(chrome::kChromeUIVoiceSearchHost); - - html_source->AddLocalizedString("loadingMessage", - IDS_VOICESEARCH_LOADING_MESSAGE); - html_source->AddLocalizedString("voiceSearchLongTitle", - IDS_VOICESEARCH_TITLE_MESSAGE); - - html_source->SetJsonPath("strings.js"); - html_source->AddResourcePath("about_voicesearch.js", - IDR_ABOUT_VOICESEARCH_JS); - html_source->SetDefaultResource(IDR_ABOUT_VOICESEARCH_HTML); - return html_source; -} - -// Helper functions for collecting a list of key-value pairs that will -// be displayed. -void AddPair16(base::ListValue* list, - const base::string16& key, - const base::string16& value) { - auto results = std::make_unique(); - results->SetString("key", key); - results->SetString("value", value); - list->Append(std::move(results)); -} - -void AddPair(base::ListValue* list, - const base::StringPiece& key, - const base::StringPiece& value) { - AddPair16(list, UTF8ToUTF16(key), UTF8ToUTF16(value)); -} - -void AddPairBool(base::ListValue* list, - const base::StringPiece& key, - bool value) { - AddPair(list, key, value ? "Yes" : "No"); -} - -// Generate an empty data-pair which acts as a line break. -void AddLineBreak(base::ListValue* list) { - AddPair(list, "", ""); -} - -void AddSharedModulePlatformsOnBlockingTaskRunner(base::ListValue* list, - const base::FilePath& path) { - base::AssertBlockingAllowed(); - - if (path.empty()) - return; - - // Display available platforms for shared module. - base::FilePath platforms_path = path.AppendASCII("_platform_specific"); - base::FileEnumerator enumerator(platforms_path, false, - base::FileEnumerator::DIRECTORIES); - base::string16 files; - for (base::FilePath name = enumerator.Next(); !name.empty(); - name = enumerator.Next()) { - files += name.BaseName().LossyDisplayName() + ASCIIToUTF16(" "); - } - AddPair16(list, ASCIIToUTF16("Shared Module Platforms"), - files.empty() ? ASCIIToUTF16("undefined") : files); - AddLineBreak(list); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// VoiceSearchDomHandler -// -//////////////////////////////////////////////////////////////////////////////// - -// The handler for Javascript messages for the about:flags page. -class VoiceSearchDomHandler : public WebUIMessageHandler { - public: - explicit VoiceSearchDomHandler(Profile* profile) - : profile_(profile), weak_factory_(this) {} - - ~VoiceSearchDomHandler() override {} - - // WebUIMessageHandler implementation. - void RegisterMessages() override { - web_ui()->RegisterMessageCallback( - "requestVoiceSearchInfo", - base::Bind(&VoiceSearchDomHandler::HandleRequestVoiceSearchInfo, - base::Unretained(this))); - } - - private: - // Callback for the "requestVoiceSearchInfo" message. No arguments. - void HandleRequestVoiceSearchInfo(const base::ListValue* args) { - PopulatePageInformation(); - } - - void ReturnVoiceSearchInfo(std::unique_ptr info) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - DCHECK(info); - base::DictionaryValue voiceSearchInfo; - voiceSearchInfo.Set("voiceSearchInfo", std::move(info)); - web_ui()->CallJavascriptFunctionUnsafe("returnVoiceSearchInfo", - voiceSearchInfo); - } - - // Fill in the data to be displayed on the page. - void PopulatePageInformation() { - // Store Key-Value pairs of about-information. - auto list = std::make_unique(); - - // Populate information. - AddOperatingSystemInfo(list.get()); - AddAudioInfo(list.get()); - AddLanguageInfo(list.get()); - AddHotwordInfo(list.get()); - AddAppListInfo(list.get()); - - AddExtensionInfo(extension_misc::kHotwordNewExtensionId, "Extension", - list.get()); - - AddExtensionInfo(extension_misc::kHotwordSharedModuleId, "Shared Module", - list.get()); - - base::FilePath path; - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile_); - if (extension_system) { - ExtensionService* extension_service = - extension_system->extension_service(); - const extensions::Extension* extension = - extension_service->GetExtensionById( - extension_misc::kHotwordSharedModuleId, true); - if (extension) - path = extension->path(); - } - base::ListValue* raw_list = list.get(); - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::TaskPriority::USER_VISIBLE, base::MayBlock()}, - base::BindOnce(&AddSharedModulePlatformsOnBlockingTaskRunner, raw_list, - path), - base::BindOnce(&VoiceSearchDomHandler::ReturnVoiceSearchInfo, - weak_factory_.GetWeakPtr(), - base::Passed(std::move(list)))); - } - - // Adds information regarding the system and chrome version info to list. - void AddOperatingSystemInfo(base::ListValue* list) { - // Obtain the Chrome version info. - AddPair(list, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), - version_info::GetVersionNumber() + " (" + - chrome::GetChannelString() + ")"); - - // OS version information. - std::string os_label = version_info::GetOSType(); - AddPair(list, l10n_util::GetStringUTF8(IDS_VERSION_UI_OS), os_label); - - AddLineBreak(list); - } - - // Adds information regarding audio to the list. - void AddAudioInfo(base::ListValue* list) { - // NaCl and its associated functions are not available on most mobile - // platforms. ENABLE_EXTENSIONS covers those platforms and hey would not - // allow Hotwording anyways since it is an extension. - std::string nacl_enabled = "not available"; - nacl_enabled = "No"; - // Determine if NaCl is available. - base::FilePath path; - if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) { - content::WebPluginInfo info; - PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_).get(); - if (content::PluginService::GetInstance()->GetPluginInfoByPath(path, - &info) && - plugin_prefs->IsPluginEnabled(info)) { - nacl_enabled = "Yes"; - } - } - - AddPair(list, "NaCl Enabled", nacl_enabled); - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - AddPairBool(list, "Microphone Present", - hotword_service && hotword_service->microphone_available()); - - AddPairBool(list, "Audio Capture Allowed", - profile_->GetPrefs()->GetBoolean(prefs::kAudioCaptureAllowed)); - - AddLineBreak(list); - } - - // Adds information regarding languages to the list. - void AddLanguageInfo(base::ListValue* list) { - std::string locale = - profile_->GetPrefs()->GetString(prefs::kApplicationLocale); - AddPair(list, "Current Language", locale); - AddPair(list, "Hotword Previous Language", - profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage)); - - AddLineBreak(list); - } - - // Adds information specific to the hotword configuration to the list. - void AddHotwordInfo(base::ListValue* list) { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - AddPairBool(list, "Hotword Module Installable", - hotword_service && hotword_service->IsHotwordAllowed()); - - AddPairBool(list, "Hotword Search Enabled", - profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled)); - - AddPairBool( - list, "Always-on Hotword Search Enabled", - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled)); - - AddPairBool(list, "Hotword Audio Logging Enabled", - hotword_service && hotword_service->IsOptedIntoAudioLogging()); - - AddLineBreak(list); - } - - // Adds information specific to an extension to the list. - void AddExtensionInfo(const std::string& extension_id, - const std::string& name_prefix, - base::ListValue* list) { - DCHECK(!name_prefix.empty()); - std::string version("undefined"); - std::string id("undefined"); - base::FilePath path; - - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile_); - if (extension_system) { - ExtensionService* extension_service = - extension_system->extension_service(); - const extensions::Extension* extension = - extension_service->GetExtensionById(extension_id, true); - if (extension) { - id = extension->id(); - version = extension->VersionString(); - path = extension->path(); - } - } - AddPair(list, name_prefix + " Id", id); - AddPair(list, name_prefix + " Version", version); - AddPair16( - list, ASCIIToUTF16(name_prefix + " Path"), - path.empty() ? ASCIIToUTF16("undefined") : path.LossyDisplayName()); - - extensions::ExtensionPrefs* extension_prefs = - extensions::ExtensionPrefs::Get(profile_); - int pref_state = -1; - extension_prefs->ReadPrefAsInteger(extension_id, "state", &pref_state); - std::string state; - switch (pref_state) { - case extensions::Extension::DISABLED: - state = "DISABLED"; - break; - case extensions::Extension::ENABLED: - state = "ENABLED"; - break; - case extensions::Extension::EXTERNAL_EXTENSION_UNINSTALLED: - state = "EXTERNAL_EXTENSION_UNINSTALLED"; - break; - default: - state = "undefined"; - } - - AddPair(list, name_prefix + " State", state); - - AddLineBreak(list); - } - - // Adds information specific to voice search in the app launcher to the list. - void AddAppListInfo(base::ListValue* list) { -#if BUILDFLAG(ENABLE_APP_LIST) - std::string state = "No Start Page Service"; - app_list::StartPageService* start_page_service = - app_list::StartPageService::Get(profile_); - if (start_page_service) { - app_list::SpeechRecognitionState speech_state = - start_page_service->state(); - switch (speech_state) { - case app_list::SPEECH_RECOGNITION_OFF: - state = "SPEECH_RECOGNITION_OFF"; - break; - case app_list::SPEECH_RECOGNITION_READY: - state = "SPEECH_RECOGNITION_READY"; - break; - case app_list::SPEECH_RECOGNITION_HOTWORD_LISTENING: - state = "SPEECH_RECOGNITION_HOTWORD_LISTENING"; - break; - case app_list::SPEECH_RECOGNITION_RECOGNIZING: - state = "SPEECH_RECOGNITION_RECOGNIZING"; - break; - case app_list::SPEECH_RECOGNITION_IN_SPEECH: - state = "SPEECH_RECOGNITION_IN_SPEECH"; - break; - case app_list::SPEECH_RECOGNITION_STOPPING: - state = "SPEECH_RECOGNITION_STOPPING"; - break; - case app_list::SPEECH_RECOGNITION_NETWORK_ERROR: - state = "SPEECH_RECOGNITION_NETWORK_ERROR"; - break; - default: - state = "undefined"; - } - } - AddPair(list, "Start Page State", state); - AddLineBreak(list); -#endif - } - - Profile* const profile_; - base::WeakPtrFactory weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(VoiceSearchDomHandler); -}; - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// VoiceSearchUI -// -/////////////////////////////////////////////////////////////////////////////// - -VoiceSearchUI::VoiceSearchUI(content::WebUI* web_ui) - : content::WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - web_ui->AddMessageHandler(std::make_unique(profile)); - - // Set up the about:voicesearch source. - content::WebUIDataSource::Add(profile, CreateVoiceSearchUiHtmlSource()); -} - -VoiceSearchUI::~VoiceSearchUI() {} diff --git a/chrome/browser/ui/webui/chromeos/voice_search_ui.h b/chrome/browser/ui/webui/chromeos/voice_search_ui.h deleted file mode 100644 index d3e504444df2b..0000000000000 --- a/chrome/browser/ui/webui/chromeos/voice_search_ui.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_ - -#include "base/macros.h" -#include "content/public/browser/web_ui_controller.h" - -// The WebUI handler for chrome://voicesearch. -class VoiceSearchUI : public content::WebUIController { - public: - explicit VoiceSearchUI(content::WebUI* web_ui); - ~VoiceSearchUI() override; - - private: - DISALLOW_COPY_AND_ASSIGN(VoiceSearchUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_CHROMEOS_VOICE_SEARCH_UI_H_ diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index a7c1486bde890..18cfae0e4c8ce 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc @@ -1680,7 +1680,6 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) { {"searchPageTitle", IDS_SETTINGS_SEARCH}, #endif {"searchEnginesManage", IDS_SETTINGS_SEARCH_MANAGE_SEARCH_ENGINES}, - {"searchOkGoogleLabel", IDS_SETTINGS_SEARCH_OK_GOOGLE_LABEL}, #if defined(OS_CHROMEOS) {"searchGoogleAssistant", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT}, {"searchGoogleAssistantEnabled", @@ -1688,26 +1687,10 @@ void AddSearchStrings(content::WebUIDataSource* html_source, Profile* profile) { {"searchGoogleAssistantDisabled", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT_DISABLED}, {"assistantTurnOn", IDS_SETTINGS_SEARCH_GOOGLE_ASSISTANT_TURN_ON}, -#endif - {"searchOkGoogleSubtextAlwaysOn", - IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_ALWAYS_ON}, - {"searchOkGoogleSubtextNoHardware", - IDS_SETTINGS_SEARCH_OK_GOOGLE_SUBTEXT_NO_HARDWARE}, - {"searchOkGoogleAudioHistoryLabel", - IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_LABEL}, - {"searchOkGoogleAudioHistorySubtext", - IDS_SETTINGS_SEARCH_OK_GOOGLE_AUDIO_HISTORY_SUBTEXT}, - {"searchOkGoogleRetrain", IDS_SETTINGS_SEARCH_OK_GOOGLE_RETRAIN}, -#if defined(OS_CHROMEOS) - {"searchOkGoogleDisabled", IDS_SETTINGS_SEARCH_OK_GOOGLE_DISABLED}, #endif }; AddLocalizedStringsBulk(html_source, localized_strings, arraysize(localized_strings)); - html_source->AddString("hotwordLearnMoreUrl", - chrome::kHotwordLearnMoreURL); - html_source->AddString("manageAudioHistoryUrl", - chrome::kManageAudioHistoryURL); base::string16 search_explanation_text = l10n_util::GetStringFUTF16( IDS_SETTINGS_SEARCH_EXPLANATION, base::ASCIIToUTF16(chrome::kOmniboxLearnMoreURL)); diff --git a/chrome/browser/ui/webui/settings/search_engines_handler.cc b/chrome/browser/ui/webui/settings/search_engines_handler.cc index 3f932cd6ce277..a283cd80bd50b 100644 --- a/chrome/browser/ui/webui/settings/search_engines_handler.cc +++ b/chrome/browser/ui/webui/settings/search_engines_handler.cc @@ -4,6 +4,8 @@ #include "chrome/browser/ui/webui/settings/search_engines_handler.h" +#include +#include #include #include "base/bind.h" @@ -15,9 +17,6 @@ #include "base/values.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/search/hotword_audio_history_handler.h" -#include "chrome/browser/search/hotword_service.h" -#include "chrome/browser/search/hotword_service_factory.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "chrome/browser/signin/signin_manager_factory.h" @@ -43,35 +42,9 @@ const char kSearchEngineField[] = "searchEngine"; const char kKeywordField[] = "keyword"; const char kQueryUrlField[] = "queryUrl"; -// Fields for hotwordUpdateInfo result. -const char kHotwordSatusAllowed[] = "allowed"; -const char kHotwordSatusEnabled[] = "enabled"; -const char kHotwordStatusAlwaysOn[] = "alwaysOn"; -const char kHotwordSatusErrorMessage[] = "errorMessage"; -const char kHotwordSatusUserUserName[] = "userName"; -const char kHotwordSatusHistoryEnabled[] = "historyEnabled"; - // Dummy number used for indicating that a new search engine is added. const int kNewSearchEngineIndex = -1; -bool IsGoogleDefaultSearch(Profile* profile) { - TemplateURLService* template_url_service = - TemplateURLServiceFactory::GetForProfile(profile); - if (!template_url_service) - return false; - const TemplateURL* url_template = - template_url_service->GetDefaultSearchProvider(); - return url_template && - url_template->url_ref().HasGoogleBaseURLs( - template_url_service->search_terms_data()); -} - -bool GetHotwordAlwaysOn(Profile* profile) { - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile); - return signin && signin->IsAuthenticated() && - HotwordServiceFactory::IsAlwaysOnAvailable(); -} - } // namespace namespace settings { @@ -116,23 +89,10 @@ void SearchEnginesHandler::RegisterMessages() { "searchEngineEditCompleted", base::Bind(&SearchEnginesHandler::HandleSearchEngineEditCompleted, base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "getHotwordInfo", base::Bind(&SearchEnginesHandler::HandleGetHotwordInfo, - base::Unretained(this))); - web_ui()->RegisterMessageCallback( - "setHotwordSearchEnabled", - base::Bind(&SearchEnginesHandler::HandleSetHotwordSearchEnabled, - base::Unretained(this))); } void SearchEnginesHandler::OnJavascriptAllowed() { list_controller_.table_model()->SetObserver(this); - pref_change_registrar_.Add(prefs::kHotwordSearchEnabled, - base::Bind(&SearchEnginesHandler::SendHotwordInfo, - base::Unretained(this))); - pref_change_registrar_.Add(prefs::kHotwordAlwaysOnSearchEnabled, - base::Bind(&SearchEnginesHandler::SendHotwordInfo, - base::Unretained(this))); } void SearchEnginesHandler::OnJavascriptDisallowed() { @@ -274,18 +234,6 @@ void SearchEnginesHandler::HandleSetDefaultSearchEngine( list_controller_.MakeDefaultTemplateURL(index); - // If the new search engine is not Google, disable hotword search. - // TODO(stevenjb): Investigate migrating this logic to - // MakeDefaultTemplateURL. - if (!IsGoogleDefaultSearch(profile_)) { - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - if (hotword_service) - hotword_service->DisableHotwordPreferences(); - } - // Hotword status may have changed. - SendHotwordInfo(); - base::RecordAction(base::UserMetricsAction("Options_SearchEngineSetDefault")); } @@ -399,137 +347,4 @@ void SearchEnginesHandler::HandleSearchEngineEditCompleted( } } -void SearchEnginesHandler::HandleGetHotwordInfo(const base::ListValue* args) { - AllowJavascript(); - - std::unique_ptr callback_id; - if (args) { - CHECK_EQ(1U, args->GetSize()); - const base::Value* id; - CHECK(args->Get(0, &id)); - callback_id = id->CreateDeepCopy(); - } - - std::unique_ptr status = GetHotwordInfo(); - bool enabled = false; - status->GetBoolean(kHotwordSatusEnabled, &enabled); - bool always_on = false; - status->GetBoolean(kHotwordStatusAlwaysOn, &always_on); - if (!enabled || !always_on) { - HotwordInfoComplete(callback_id.get(), *status); - return; - } - - // OnGetHotwordAudioHistoryEnabled will call HotwordInfoComplete(). - HotwordServiceFactory::GetForProfile(profile_) - ->GetAudioHistoryHandler() - ->GetAudioHistoryEnabled( - base::Bind(&SearchEnginesHandler::OnGetHotwordAudioHistoryEnabled, - weak_ptr_factory_.GetWeakPtr(), base::Passed(&callback_id), - base::Passed(&status))); -} - -std::unique_ptr SearchEnginesHandler::GetHotwordInfo() { - auto status = base::MakeUnique(); - if (!IsGoogleDefaultSearch(profile_)) { - status->SetBoolean(kHotwordSatusAllowed, false); - return status; - } - - status->SetBoolean(kHotwordSatusAllowed, - HotwordServiceFactory::IsHotwordAllowed(profile_)); - - HotwordServiceFactory::IsServiceAvailable(profile_); // Update error value. - int hotword_error = HotwordServiceFactory::GetCurrentError(profile_); - if (hotword_error) { - base::string16 hotword_error_message; - if (hotword_error != IDS_HOTWORD_GENERIC_ERROR_MESSAGE) { - hotword_error_message = l10n_util::GetStringUTF16(hotword_error); - } else { - hotword_error_message = l10n_util::GetStringFUTF16( - hotword_error, base::ASCIIToUTF16(chrome::kHotwordLearnMoreURL)); - } - status->SetString(kHotwordSatusErrorMessage, hotword_error_message); - } - - if (!HotwordServiceFactory::GetForProfile(profile_)) { - status->SetBoolean(kHotwordSatusEnabled, false); - return status; - } - - bool always_on = GetHotwordAlwaysOn(profile_); - status->SetBoolean(kHotwordStatusAlwaysOn, always_on); - - std::string pref_name = always_on ? prefs::kHotwordAlwaysOnSearchEnabled - : prefs::kHotwordSearchEnabled; - bool enabled = profile_->GetPrefs()->GetBoolean(pref_name); - status->SetBoolean(kHotwordSatusEnabled, enabled); - if (!enabled) - return status; - - SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile_); - std::string user_display_name = - signin ? signin->GetAuthenticatedAccountInfo().email : ""; - status->SetString(kHotwordSatusUserUserName, user_display_name); - return status; -} - -void SearchEnginesHandler::OnGetHotwordAudioHistoryEnabled( - std::unique_ptr callback_id, - std::unique_ptr status, - bool success, - bool logging_enabled) { - if (success) - status->SetBoolean(kHotwordSatusHistoryEnabled, logging_enabled); - HotwordInfoComplete(callback_id.get(), *status); -} - -void SearchEnginesHandler::HotwordInfoComplete( - const base::Value* callback_id, - const base::DictionaryValue& status) { - if (callback_id) - ResolveJavascriptCallback(*callback_id, status); - else - FireWebUIListener("hotword-info-update", status); -} - -void SearchEnginesHandler::SendHotwordInfo() { - HandleGetHotwordInfo(nullptr); -} - -void SearchEnginesHandler::HandleSetHotwordSearchEnabled( - const base::ListValue* args) { - CHECK_EQ(1U, args->GetSize()); - bool enabled; - CHECK(args->GetBoolean(0, &enabled)); - - bool always_on = GetHotwordAlwaysOn(profile_); - if (!always_on) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, enabled); - return; - } - - HotwordService* hotword_service = - HotwordServiceFactory::GetForProfile(profile_); - if (!enabled || !hotword_service) { - profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, - false); - return; - } - - bool was_enabled = - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled); - HotwordService::LaunchMode launch_mode; - if (was_enabled) { - launch_mode = HotwordService::RETRAIN; - } else { - bool logging_enabled = - profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled); - launch_mode = logging_enabled ? HotwordService::HOTWORD_ONLY - : HotwordService::HOTWORD_AND_AUDIO_HISTORY; - } - hotword_service->OptIntoHotwording(launch_mode); - SendHotwordInfo(); -} - } // namespace settings diff --git a/chrome/browser/ui/webui/settings/search_engines_handler.h b/chrome/browser/ui/webui/settings/search_engines_handler.h index 30d4f2f3de319..b764a280ba424 100644 --- a/chrome/browser/ui/webui/settings/search_engines_handler.h +++ b/chrome/browser/ui/webui/settings/search_engines_handler.h @@ -6,6 +6,7 @@ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_SEARCH_ENGINES_HANDLER_H_ #include +#include #include "base/macros.h" #include "base/memory/weak_ptr.h" @@ -20,7 +21,6 @@ class Profile; namespace base { class DictionaryValue; class ListValue; -class Value; } namespace extensions { @@ -96,29 +96,6 @@ class SearchEnginesHandler : public SettingsPageUIHandler, base::DictionaryValue* CreateDictionaryForExtension( const extensions::Extension& extension); - // WebUI call to request a dictionary of hotword related properties. - void HandleGetHotwordInfo(const base::ListValue* args); - - // Constructs a SearchPageHotwordInfo dictionary. - std::unique_ptr GetHotwordInfo(); - - // Callback for HotwordService::AudioHistoryHandler::GetAudioHistoryEnabled. - void OnGetHotwordAudioHistoryEnabled( - std::unique_ptr callback_id, - std::unique_ptr status, - bool success, - bool logging_enabled); - - // Calls either ResolveJavascriptCallback or CallJavascriptFunction. - void HotwordInfoComplete(const base::Value* callback_id, - const base::DictionaryValue& status); - - // Calls WebUI to send hotword search info updates. - void SendHotwordInfo(); - - // WebUI call to enable hotword search. - void HandleSetHotwordSearchEnabled(const base::ListValue* args); - Profile* const profile_; KeywordEditorController list_controller_; diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index 4dca90bc97cec..7fb3d11e03e0f 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc @@ -311,9 +311,6 @@ const char kEnableDomainReliability[] = "enable-domain-reliability"; const char kEnableExperimentalFullscreenExitUI[] = "enable-experimental-fullscreen-exit-ui"; -// Enables experimental hotword features specific to always-on. -const char kEnableExperimentalHotwordHardware[] = "enable-hotword-hardware"; - // Enables logging for extension activity. const char kEnableExtensionActivityLogging[] = "enable-extension-activity-logging"; diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index e5bab429665bb..e62d8c92210f3 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h @@ -104,7 +104,6 @@ extern const char kEnableDeviceDiscoveryNotifications[]; extern const char kEnableDevToolsExperiments[]; extern const char kEnableDomainReliability[]; extern const char kEnableExperimentalFullscreenExitUI[]; -extern const char kEnableExperimentalHotwordHardware[]; extern const char kEnableExtensionActivityLogging[]; extern const char kEnableExtensionActivityLogTesting[]; extern const char kEnableFastUnload[]; diff --git a/chrome/common/extensions/api/BUILD.gn b/chrome/common/extensions/api/BUILD.gn index 6654e6c88f557..f6fc7b854faee 100644 --- a/chrome/common/extensions/api/BUILD.gn +++ b/chrome/common/extensions/api/BUILD.gn @@ -45,7 +45,6 @@ schema_sources = [ "font_settings.json", "gcm.json", "history.json", - "hotword_private.idl", "i18n.json", "identity.idl", "identity_private.idl", diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 18c2c6ea19cab..f6cad51032c90 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json @@ -501,10 +501,6 @@ "dependencies": ["permission:history"], "contexts": ["blessed_extension"] }, - "hotwordPrivate": { - "dependencies": ["permission:hotwordPrivate"], - "contexts": ["blessed_extension"] - }, "i18n": { "channel": "stable", "extension_types": ["extension", "legacy_packaged_app", "platform_app"], diff --git a/chrome/common/extensions/api/_permission_features.json b/chrome/common/extensions/api/_permission_features.json index 57aaf34668e16..70661c8a7938c 100644 --- a/chrome/common/extensions/api/_permission_features.json +++ b/chrome/common/extensions/api/_permission_features.json @@ -365,14 +365,6 @@ "channel": "stable", "extension_types": ["extension", "legacy_packaged_app"] }, - "hotwordPrivate": { - "channel": "stable", - "extension_types": ["extension", "platform_app"], - "whitelist": [ - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // hotword component - "B6356EFF4047BC5F868C7D91868B6F5C01951A8A" // hotword_audio_verification - ] - }, "identity": { "channel": "stable", "extension_types": ["extension", "platform_app"] diff --git a/chrome/common/extensions/api/hotword_private.idl b/chrome/common/extensions/api/hotword_private.idl deleted file mode 100644 index a7ffeb1a2449e..0000000000000 --- a/chrome/common/extensions/api/hotword_private.idl +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// The chrome.hotwordPrivate API allows extensions to access and -// mutate the preference for enabling hotword search. It also provides -// information on whether the hotword search is available. This API provides an -// event interface to transmit to the extension a signal that the preference fo -// hotword search has change. -// -// For an FYI, visit http://goo.gl/AyHbkH - -namespace hotwordPrivate { - - dictionary StatusDetails { - // Whether the hotword preference has been set. - boolean enabledSet; - - // If the hotword extension is enabled. Will always be false if |available| - // is false. - boolean enabled; - - // Whether the hotword extension is available to be enabled - // Optional field, only valid when getStatus() is called with - // |getOptionalFields| = true. Otherwise, set to false. - boolean available; - - // Whether always-on is available to be enabled - // Optional field, only valid when getStatus() is called with - // |getOptionalFields| = true. Otherwise, set to false. - boolean alwaysOnAvailable; - - // Whether the sound of "Ok, Google" plus a few seconds before is sent - // back to Google. - boolean audioLoggingEnabled; - - // Whether always-on hotwording is enabled. - boolean alwaysOnEnabled; - - // Whether training mode is enabled. - boolean trainingEnabled; - - // Whether the user corresponding to this profile is the active user. - boolean userIsActive; - - // Whether hotword hardware is available if requested. - boolean hotwordHardwareAvailable; - }; - - dictionary LaunchState { - // TODO(kcarattini): Consider adding more variables here, - // such as the available state of the hotword service. - - // The mode that the Hotword Audio Verification app was launched in. - long launchMode; - }; - - dictionary LogDetails { - // Number of audio channels. i.e. 1 = mono, 2 = stereo - long channels; - - // Bytes per sample per channel. - long bytes_per_sample; - - // Sample rate. Usually 32000 or 44100, but may be any integer. - long sample_rate; - - // Array containing audio data. Length is - // (channels * bytes_per_sample * sample_rate * ). - ArrayBuffer buffer; - }; - - dictionary AudioHistoryState { - // Whether the call to set or get this state was successful. - boolean success; - - // The current value of the audio history opt-in state after this - // call. - boolean enabled; - }; - - // The type of the recognized hotword. Right now it only has 'search' but - // could be expanded to other types of actions in the future. - enum HotwordType { search }; - - callback GenericDoneCallback = void (); - callback LaunchStateCallback = void(LaunchState result); - callback LocalizeStringsCallback = void(object result); - callback StatusDetailsCallback = void(StatusDetails result); - callback AudioHistoryCallback = void(AudioHistoryState result); - - interface Functions { - // Sets the current enabled state of hotword search. - // True: enable hotword search. False: disable hotword search. - static void setEnabled(boolean state, - optional GenericDoneCallback callback); - - // Retrieves the current state of hotword search. - // The result is put into a StatusDetails object. - // |getOptionalFields|: If true, fills in fields tagged as optional in - // StatusDetails with valid values. These fields are not valid by default - // since their current implementations may cause blocking operations. - static void getStatus(optional boolean getOptionalFields, - StatusDetailsCallback callback); - - // Retrieves a dictionary mapping names to localized resource strings. - static void getLocalizedStrings(LocalizeStringsCallback callback); - - // Sets the current enabled state of audio logging in the extension. - // True: logging enabled. False: no logging. - static void setAudioLoggingEnabled(boolean state, - optional GenericDoneCallback callback); - - // Sets the current enabled state of hotword-always-on-search pref. - // True: enable hotword always on search. - // False: disable hotword always on search. - static void setHotwordAlwaysOnSearchEnabled(boolean state, - optional GenericDoneCallback callback); - - // Sets the current state of the browser-requested hotword session. - static void setHotwordSessionState(boolean started, - optional GenericDoneCallback callback); - - // Notifies that a hotword has been recognized in the browser-requested - // hotword session. - static void notifyHotwordRecognition(HotwordType type, - optional LogDetails log, - optional GenericDoneCallback callback); - - // Retrieves the state that the Hotword Audio Verification app was - // launched in. The result is put into a LaunchState object. - static void getLaunchState(LaunchStateCallback callback); - - // Starts the speaker model training. - static void startTraining(optional GenericDoneCallback callback); - - // Finalizess the speaker model. - static void finalizeSpeakerModel(optional GenericDoneCallback callback); - - // Notifies that the speaker model has been saved. - static void notifySpeakerModelSaved(optional GenericDoneCallback callback); - - // Stops the speaker model training. - static void stopTraining(optional GenericDoneCallback callback); - - // Sets the audio history opt-in state. - static void setAudioHistoryEnabled(boolean enabled, - optional AudioHistoryCallback callback); - - // Gets the audio history opt-in state. - static void getAudioHistoryEnabled(optional AudioHistoryCallback callback); - - // Sends the result of whether a speaker model exists to the browser. - static void speakerModelExistsResult(boolean exists, - optional GenericDoneCallback callback); - }; - - interface Events { - // Fired when the hotword detector enabled state should be changed. - // This can be from various sources, e.g. a pref change or training - // a speaker model. - static void onEnabledChanged(); - - // Fired when the browser wants to start a hotword session. - static void onHotwordSessionRequested(); - - // Fired when the browser wants to stop the requested hotword session. - static void onHotwordSessionStopped(); - - // Fired when the speaker model should be finalized. - static void onFinalizeSpeakerModel(); - - // Fired when the speaker model has been saved. - static void onSpeakerModelSaved(); - - // Fired when a hotword has triggered. - static void onHotwordTriggered(); - - // Fired when the speaker model should be deleted. - static void onDeleteSpeakerModel(); - - // Fired when the browser wants to find out whether the speaker model - // exists. - static void onSpeakerModelExists(); - - // Fired when the microphone state changes. - static void onMicrophoneStateChanged(boolean enabled); - }; -}; diff --git a/chrome/common/extensions/api/privacy.json b/chrome/common/extensions/api/privacy.json index 22688768e89d0..1acf9c7794a0d 100644 --- a/chrome/common/extensions/api/privacy.json +++ b/chrome/common/extensions/api/privacy.json @@ -59,11 +59,6 @@ "value": ["autofillEnabled", {"type":"boolean"}], "description": "If enabled, Chrome offers to automatically fill in forms. This preference's value is a boolean, defaulting to true." }, - "hotwordSearchEnabled": { - "$ref": "types.ChromeSetting", - "value": ["hotwordSearchEnabled", {"type":"boolean"}], - "description": "If enabled, Chrome will enable 'OK, Google' to start a voice search. This preference's value is a boolean, defaulting to true." - }, "passwordSavingEnabled": { "$ref": "types.ChromeSetting", "value": ["passwordSavingEnabled", {"type":"boolean"}], diff --git a/chrome/common/extensions/extension_constants.cc b/chrome/common/extensions/extension_constants.cc index 819c0c64fc64a..20c8370047f4e 100644 --- a/chrome/common/extensions/extension_constants.cc +++ b/chrome/common/extensions/extension_constants.cc @@ -57,10 +57,6 @@ const char kHTermAppId[] = "pnhechapfaindjhompbnflcldabbghjo"; const char kHTermDevAppId[] = "okddffdblfhhnmhodogpojmfkjmhinfp"; const char kIdentityApiUiAppId[] = "ahjaciijnoiaklcomgnblndopackapon"; const char kCroshBuiltinAppId[] = "nkoccljplnhpfnfiajclkommnmllphnl"; -const char kHotwordAudioVerificationAppId[] = - "abjokfonkihficiokmkfboogholifghn"; -const char kHotwordNewExtensionId[] = "nbpagnldghgfoolbancepceaanlmhfmd"; -const char kHotwordSharedModuleId[] = "lccekmodgklaepjeofjdjpbminllajkg"; const char kTextEditorAppId[] = "mmfbcljfglbokpmkimbfghdkjmjhdgbg"; const char kYoutubeAppId[] = "blpcfgokakmgnkcojhhkbfbldkacnbeo"; const char kInAppPaymentsSupportAppId[] = "nmmhkkegccagdldgiimedpiccmgmieda"; diff --git a/chrome/common/extensions/extension_constants.h b/chrome/common/extensions/extension_constants.h index d5c1db0d20f79..8b221cf5e1f54 100644 --- a/chrome/common/extensions/extension_constants.h +++ b/chrome/common/extensions/extension_constants.h @@ -115,15 +115,6 @@ extern const char kIdentityApiUiAppId[]; // The extension id of the Crosh component app for ChromeOS. extern const char kCroshBuiltinAppId[]; -// The extension id of the hotword audio verification dialogue app. -extern const char kHotwordAudioVerificationAppId[]; - -// The extension id of the new (experimental) hotword extension. -extern const char kHotwordNewExtensionId[]; - -// The extension id of the hotword shared module. -extern const char kHotwordSharedModuleId[]; - // The extension id of the Text Editor application. extern const char kTextEditorAppId[]; diff --git a/chrome/common/extensions/permissions/chrome_api_permissions.cc b/chrome/common/extensions/permissions/chrome_api_permissions.cc index 49c594ba79f53..2f5294815f442 100644 --- a/chrome/common/extensions/permissions/chrome_api_permissions.cc +++ b/chrome/common/extensions/permissions/chrome_api_permissions.cc @@ -125,8 +125,6 @@ ChromeAPIPermissions::GetAllPermissions() const { APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kFileManagerPrivate, "fileManagerPrivate", APIPermissionInfo::kFlagCannotBeOptional}, - {APIPermission::kHotwordPrivate, "hotwordPrivate", - APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kIdentityPrivate, "identityPrivate", APIPermissionInfo::kFlagCannotBeOptional}, {APIPermission::kWebcamPrivate, "webcamPrivate"}, diff --git a/chrome/common/extensions/permissions/permission_set_unittest.cc b/chrome/common/extensions/permissions/permission_set_unittest.cc index 5b819229c3b7b..e4f01497d2602 100644 --- a/chrome/common/extensions/permissions/permission_set_unittest.cc +++ b/chrome/common/extensions/permissions/permission_set_unittest.cc @@ -821,7 +821,6 @@ TEST(PermissionsTest, PermissionMessages) { skip.insert(APIPermission::kFileBrowserHandlerInternal); skip.insert(APIPermission::kFileManagerPrivate); skip.insert(APIPermission::kFirstRunPrivate); - skip.insert(APIPermission::kHotwordPrivate); skip.insert(APIPermission::kIdentityPrivate); skip.insert(APIPermission::kInputMethodPrivate); skip.insert(APIPermission::kLanguageSettingsPrivate); diff --git a/chrome/common/features.gni b/chrome/common/features.gni index e25c86f18c1d6..f9561c75cfc6b 100644 --- a/chrome/common/features.gni +++ b/chrome/common/features.gni @@ -38,10 +38,6 @@ declare_args() { # It is enableable separately to facilitate testing. enable_hangout_services_extension = is_chrome_branded - # 'Ok Google' hotwording is disabled to prepare for its removal. - # http://crbug.com/755579 - enable_hotwording = false - # Enables usage of the system-provided notification center. enable_native_notifications = is_android || is_mac || is_win || (is_desktop_linux && use_dbus) || is_chromeos @@ -86,7 +82,6 @@ chrome_grit_defines = [ "enable_extensions=$enable_extensions", "enable_google_now=$enable_google_now", "enable_hangout_services_extension=$enable_hangout_services_extension", - "enable_hotwording=$enable_hotwording", "enable_plugins=$enable_plugins", "enable_print_preview=$enable_print_preview", "enable_printing=$_enable_printing", diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 53bf29f9af686..53098bd933823 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc @@ -1713,30 +1713,6 @@ const char kVideoCaptureAllowed[] = "hardware.video_capture_enabled"; // capture devices without prompt. const char kVideoCaptureAllowedUrls[] = "hardware.video_capture_allowed_urls"; -// A boolean pref that controls the enabled-state of hotword search voice -// trigger. -const char kHotwordSearchEnabled[] = "hotword.search_enabled_2"; - -// A boolean pref that controls the enabled-state of hotword search voice -// trigger from any screen. -const char kHotwordAlwaysOnSearchEnabled[] = "hotword.always_on_search_enabled"; - -// A boolean pref that indicates whether the hotword always-on notification -// has been seen already. -const char kHotwordAlwaysOnNotificationSeen[] = - "hotword.always_on_notification_seen"; - -// A boolean pref that controls whether the sound of "Ok, Google" plus a few -// seconds of audio data before and the spoken query are sent back to be stored -// in a user's Voice & Audio Activity. Updated whenever the user opens -// chrome://settings and also polled for every 24 hours. -const char kHotwordAudioLoggingEnabled[] = "hotword.audio_logging_enabled"; - -// A string holding the locale information under which Hotword was installed. -// It is used for comparison since the hotword voice search trigger must be -// reinstalled to handle a new language. -const char kHotwordPreviousLanguage[] = "hotword.previous_language"; - #if defined(OS_CHROMEOS) // Dictionary for transient storage of settings that should go into device // settings storage before owner has been assigned. diff --git a/chrome/common/pref_names.h b/chrome/common/pref_names.h index 2c7f5e1b75ab0..077cf87aae99b 100644 --- a/chrome/common/pref_names.h +++ b/chrome/common/pref_names.h @@ -612,12 +612,6 @@ extern const char kAudioCaptureAllowedUrls[]; extern const char kVideoCaptureAllowed[]; extern const char kVideoCaptureAllowedUrls[]; -extern const char kHotwordSearchEnabled[]; -extern const char kHotwordAlwaysOnSearchEnabled[]; -extern const char kHotwordAlwaysOnNotificationSeen[]; -extern const char kHotwordAudioLoggingEnabled[]; -extern const char kHotwordPreviousLanguage[]; - #if defined(OS_CHROMEOS) extern const char kDeviceSettingsCache[]; extern const char kHardwareKeyboardLayout[]; diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index c639a3173e434..552f2fee59bc1 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc @@ -209,12 +209,6 @@ const char kBlockedPluginLearnMoreURL[] = "https://support.google.com/chrome/?p=ib_blocked_plugin"; #endif -const char kHotwordLearnMoreURL[] = - "https://support.google.com/chrome/?p=ui_hotword_search"; - -const char kManageAudioHistoryURL[] = - "https://history.google.com/history/audio"; - const char kLearnMoreRegisterProtocolHandlerURL[] = "https://support.google.com/chrome/?p=ib_protocol_handler"; diff --git a/chrome/common/url_constants.h b/chrome/common/url_constants.h index 362854f928a7f..b0002a1050343 100644 --- a/chrome/common/url_constants.h +++ b/chrome/common/url_constants.h @@ -148,12 +148,6 @@ extern const char kOutdatedPluginLearnMoreURL[]; // The URL for the "Learn more" page for the blocked plugin infobar. extern const char kBlockedPluginLearnMoreURL[]; -// The URL for the "Learn more" page for hotword search voice trigger. -extern const char kHotwordLearnMoreURL[]; - -// The URL for managing a user's audio history. -extern const char kManageAudioHistoryURL[]; - // The URL for the "Learn more" page for register protocol handler infobars. extern const char kLearnMoreRegisterProtocolHandlerURL[]; diff --git a/chrome/common/webui_url_constants.cc b/chrome/common/webui_url_constants.cc index 54169370d36a4..9eba678f2ac02 100644 --- a/chrome/common/webui_url_constants.cc +++ b/chrome/common/webui_url_constants.cc @@ -215,7 +215,6 @@ const char kChromeUISysInternalsHost[] = "sys-internals"; const char kChromeUITermsOemURL[] = "chrome://terms/oem"; const char kChromeUIUserImageHost[] = "userimage"; const char kChromeUIUserImageURL[] = "chrome://userimage/"; -const char kChromeUIVoiceSearchHost[] = "voicesearch"; #endif // defined(OS_CHROMEOS) #if defined(OS_WIN) @@ -381,7 +380,6 @@ const char* const kChromeHostURLs[] = { kChromeUIPowerHost, kChromeUIInternetConfigDialogHost, kChromeUIInternetDetailDialogHost, - kChromeUIVoiceSearchHost, #endif #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) kChromeUIDiscardsHost, diff --git a/chrome/common/webui_url_constants.h b/chrome/common/webui_url_constants.h index ddc485cefe04e..113561f6e7684 100644 --- a/chrome/common/webui_url_constants.h +++ b/chrome/common/webui_url_constants.h @@ -212,7 +212,6 @@ extern const char kChromeUISysInternalsHost[]; extern const char kChromeUITermsOemURL[]; extern const char kChromeUIUserImageHost[]; extern const char kChromeUIUserImageURL[]; -extern const char kChromeUIVoiceSearchHost[]; #endif // defined(OS_CHROMEOS) #if defined(OS_WIN) diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 7cd6a387ac919..34e882d6b63b4 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn @@ -652,7 +652,6 @@ test("browser_tests") { "../browser/safe_browsing/test_safe_browsing_database_helper.h", "../browser/safe_json_parser_browsertest.cc", "../browser/safe_xml_parser_browsertest.cc", - "../browser/search/hotword_installer_browsertest.cc", "../browser/search/suggestions/image_fetcher_impl_browsertest.cc", "../browser/search_engines/template_url_scraper_browsertest.cc", "../browser/secure_origin_whitelist_browsertest.cc", @@ -1232,7 +1231,6 @@ test("browser_tests") { "../browser/extensions/external_install_error_browsertest.cc", "../browser/extensions/fetch_apitest.cc", "../browser/extensions/gpu_browsertest.cc", - "../browser/extensions/hotword_browsertest.cc", "../browser/extensions/isolated_app_browsertest.cc", "../browser/extensions/lazy_background_page_apitest.cc", "../browser/extensions/lazy_background_page_test_util.h", @@ -1568,7 +1566,6 @@ test("browser_tests") { "../browser/download/notification/download_notification_browsertest.cc", "../browser/drive/drive_notification_manager_factory_browsertest.cc", "../browser/extensions/api/certificate_provider/certificate_provider_apitest.cc", - "../browser/extensions/api/hotword_private/hotword_private_apitest.cc", "../browser/extensions/api/networking_private/networking_private_apitest.cc", "../browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc", "../browser/extensions/api/vpn_provider/vpn_provider_apitest.cc", @@ -3234,7 +3231,6 @@ test("unit_tests") { "../browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_test_utils.cc", "../browser/safe_browsing/settings_reset_prompt/settings_reset_prompt_test_utils.h", "../browser/safe_search_api/safe_search_url_checker_unittest.cc", - "../browser/search/hotword_service_unittest.cc", "../browser/signin/easy_unlock_app_manager_unittest.cc", "../browser/signin/easy_unlock_auth_attempt_unittest.cc", "../browser/signin/easy_unlock_notification_controller_chromeos_unittest.cc", diff --git a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json deleted file mode 100644 index a6028eece45a3..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js b/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js deleted file mode 100644 index 97f6973e215dd..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/alwaysOnEnabled/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function alwaysOnEnabled() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("alwaysOnEnabled: " + result.alwaysOnEnabled); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js b/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js deleted file mode 100644 index 12692ef26f468..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/audioHistory/test.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function audioHistory() { - chrome.hotwordPrivate.setAudioHistoryEnabled( - true, - chrome.test.callbackPass(function(state) { - if (state.success) - chrome.test.sendMessage("set AH True: "+state.enabled+" success"); - else - chrome.test.sendMessage("set AH True: "+state.enabled+" failure"); - })); - // Test with setting to false as well. - chrome.hotwordPrivate.setAudioHistoryEnabled( - false, - chrome.test.callbackPass(function(state) { - if (state.success) - chrome.test.sendMessage("set AH False: "+state.enabled+" success"); - else - chrome.test.sendMessage("set AH False: "+state.enabled+" failure"); - })); - chrome.hotwordPrivate.getAudioHistoryEnabled(chrome.test.callbackPass( - function(state) { - if (state.success) - chrome.test.sendMessage("get AH: "+state.enabled+" success"); - else - chrome.test.sendMessage("get AH: "+state.enabled+" failure"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js b/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js deleted file mode 100644 index 1e86be629ffd9..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getEnabled/test.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function getEnabled() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertFalse(result.enabledSet); - })); - - chrome.hotwordPrivate.setEnabled(true, function() {}); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabled); - })); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabledSet); - })); - - chrome.hotwordPrivate.setEnabled(false, function() {}); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertFalse(result.enabled); - })); - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.assertTrue(result.enabledSet); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json deleted file mode 100644 index a6028eece45a3..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js b/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js deleted file mode 100644 index 957d11e556beb..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/getLaunchState/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function getLaunchState() { - chrome.hotwordPrivate.getLaunchState( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("launchMode: " + - result.launchMode); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js b/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js deleted file mode 100644 index 7f58b17e5133d..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/hotwordSession/test.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function hotwordSessionTest() { - chrome.hotwordPrivate.onHotwordSessionRequested.addListener(function () { - chrome.hotwordPrivate.setHotwordSessionState(true, function() { - chrome.hotwordPrivate.notifyHotwordRecognition('search', function() { - chrome.hotwordPrivate.onHotwordSessionStopped.addListener( - function() { - // Calling setHotwordSessionState and - // notifyHotwordRecognition after stopped should be ignored. - chrome.hotwordPrivate.setHotwordSessionState(false, function() { - chrome.hotwordPrivate.notifyHotwordRecognition( - 'search', function() { - chrome.test.sendMessage("stopped"); - chrome.test.succeed(); - }); - }); - }); - chrome.test.sendMessage("stopReady"); - }); - }); - }); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js b/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js deleted file mode 100644 index aa22269619f59..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailable/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function isAvailable() { - chrome.hotwordPrivate.getStatus( - true, - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("available: " + result.available); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js b/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js deleted file mode 100644 index 01ef5b831bdf7..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/isAvailableNoGet/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function isAvailable() { - chrome.hotwordPrivate.getStatus( - chrome.test.callbackPass(function(result) { - chrome.test.sendMessage("available: " + result.available); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js b/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js deleted file mode 100644 index 3ca6852c53808..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/notifySpeakerModelSaved/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function notifySpeakerModelSaved() { - chrome.hotwordPrivate.notifySpeakerModelSaved( - chrome.test.callbackPass(function() { - chrome.test.sendMessage("speaker model saved"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js b/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js deleted file mode 100644 index aaa08e008b3f9..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onDeleteSpeakerModel/test.js +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onDeleteSpeakerModel() { - chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.hotwordPrivate.getAudioHistoryEnabled( - chrome.test.callbackPass(function(state) {})); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js b/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js deleted file mode 100644 index cd13ad6393281..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onEnabledChanged/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onEnabledChangedTest() { - chrome.hotwordPrivate.onEnabledChanged.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js b/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js deleted file mode 100644 index 18b63993bdda0..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onFinalizeSpeakerModel/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onFinalizeSpeakerModel() { - chrome.hotwordPrivate.onFinalizeSpeakerModel.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js b/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js deleted file mode 100644 index 7e62a916d8f0e..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onHotwordTriggered/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onHotwordTriggered() { - chrome.hotwordPrivate.onHotwordTriggered.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js deleted file mode 100644 index a21cd08928fae..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelExists/test.js +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onSpeakerModelExistsTest() { - chrome.hotwordPrivate.onSpeakerModelExists.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js b/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js deleted file mode 100644 index f4fc7fcd32aa9..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/onSpeakerModelSaved/test.js +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function onSpeakerModelSaved() { - chrome.hotwordPrivate.onSpeakerModelSaved.addListener(function () { - chrome.test.sendMessage("notification"); - chrome.test.succeed(); - }); - chrome.hotwordPrivate.notifySpeakerModelSaved( - chrome.test.callbackPass(function() {})); - chrome.test.sendMessage("ready"); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js deleted file mode 100644 index 58d8452c03ac2..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableFalse/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setAudioLoggingEnabledFalse() { - chrome.hotwordPrivate.setAudioLoggingEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js deleted file mode 100644 index a3c5d867ac42b..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setAudioLoggingEnableTrue/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setAudioLoggingEnabledTrue() { - chrome.hotwordPrivate.setAudioLoggingEnabled( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js deleted file mode 100644 index 32481db7d3ded..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledFalse/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setEnabledFalse() { - chrome.hotwordPrivate.setEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js deleted file mode 100644 index 1cfb2c28ab659..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setEnabledTrue/test.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setEnabledTrue() { - chrome.hotwordPrivate.setEnabled(true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js deleted file mode 100644 index d635d10b5b38c..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableFalse/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setHotwordAlwaysOnSearchEnabledFalse() { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js deleted file mode 100644 index 0835a6a14925d..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/setHotwordAlwaysOnSearchEnableTrue/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function setHotwordAlwaysOnSearchEnabledTrue() { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js deleted file mode 100644 index b0b855956223c..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultFalse/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function speakerModelExistsResultFalse() { - chrome.hotwordPrivate.speakerModelExistsResult( - false, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json deleted file mode 100644 index 59c36125a32ae..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/manifest.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "persistent": false, - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js b/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js deleted file mode 100644 index d78f68a5e3dee..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/speakerModelExistsResultTrue/test.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function speakerModelExistsResultTrue() { - chrome.hotwordPrivate.speakerModelExistsResult( - true, chrome.test.callbackPass(function() { - chrome.test.sendMessage("ready"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/startTraining/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js b/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js deleted file mode 100644 index e9636f8b6f335..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/startTraining/test.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function startTraining() { - chrome.hotwordPrivate.startTraining(chrome.test.callbackPass(function() { - chrome.test.sendMessage("start training"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json b/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json deleted file mode 100644 index 89dd7bc8ee647..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/manifest.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Private Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser tests for chrome.hotword_private API", - "background" : { - "scripts": ["test.js"] - }, - "permissions": ["hotwordPrivate"] -} diff --git a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js b/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js deleted file mode 100644 index 379899c6c2450..0000000000000 --- a/chrome/test/data/extensions/api_test/hotword_private/stopTraining/test.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -chrome.test.runTests([ - function stopTraining() { - chrome.hotwordPrivate.stopTraining(chrome.test.callbackPass(function() { - chrome.test.sendMessage("stop training"); - })); - } -]); diff --git a/chrome/test/data/extensions/api_test/preference/standard/test.js b/chrome/test/data/extensions/api_test/preference/standard/test.js index 5022a6fe35a06..13424f2b1e099 100644 --- a/chrome/test/data/extensions/api_test/preference/standard/test.js +++ b/chrome/test/data/extensions/api_test/preference/standard/test.js @@ -32,7 +32,6 @@ var preferences_to_test = [ preferences: { alternateErrorPagesEnabled: false, autofillEnabled: false, - hotwordSearchEnabled: false, passwordSavingEnabled: false, safeBrowsingEnabled: false, safeBrowsingExtendedReportingEnabled: false, diff --git a/chrome/test/data/extensions/hotword/manifest.json b/chrome/test/data/extensions/hotword/manifest.json deleted file mode 100644 index c99d6f118bdba..0000000000000 --- a/chrome/test/data/extensions/hotword/manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - // chrome-extension://cpfhkdbjfdgdebcjlifoldbijinjfifp/ - "key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCXAxIB5iu+XGtMYYJgSwMrqO+zNa3FlWeMJLOV+U1T2VL6wDU3WD9YNlioI6a6wG49AFquEbRxQwwxlvAZC1c95LBvRlnQAkEVum0KbrJ8WHTxxDEPOfITE0J1AP5j8V0WQ9jbYvUxgefIPhDPXHpdPRAxDotygTrPa33x1075wIDAQAB", - "name": "Hotword Helper Test Extension", - "version": "0.1", - "manifest_version": 2, - "description": "Browser test for hotword helper extension", - "background" : { - "scripts": ["test.js"] - } -} diff --git a/chrome/test/data/extensions/hotword/test.js b/chrome/test/data/extensions/hotword/test.js deleted file mode 100644 index 51a8c808ccd73..0000000000000 --- a/chrome/test/data/extensions/hotword/test.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Send a WAKE_UP command to the hotword helper extension. -chrome.runtime.sendMessage( - 'dnhpdliibojhegemfjheidglijccjfmc', - {type: 'wu'}); - -// Assume messages are delivered in-order. In this case, this message will be -// handled after the previous one, and indicates the test case has completed. -chrome.runtime.sendMessage( - 'dnhpdliibojhegemfjheidglijccjfmc', - {type: 'wu'}, - function() { - chrome.test.sendMessage("done"); - }); diff --git a/chrome/test/data/webui/settings/search_page_test.js b/chrome/test/data/webui/settings/search_page_test.js index 755be824027cb..875f6aeac7490 100644 --- a/chrome/test/data/webui/settings/search_page_test.js +++ b/chrome/test/data/webui/settings/search_page_test.js @@ -119,58 +119,5 @@ cr.define('settings_search_page', function() { }); }); - // Tests the UI when Hotword 'alwaysOn' is true. - test('HotwordAlwaysOn', function() { - return browserProxy.whenCalled('getSearchEnginesList').then(function() { - return browserProxy.whenCalled('getHotwordInfo'); - }).then(function() { - Polymer.dom.flush(); - assertTrue(page.hotwordInfo_.allowed); - assertTrue(page.hotwordInfo_.alwaysOn); - assertFalse(page.hotwordInfo_.enabled); - assertFalse(browserProxy.hotwordSearchEnabled); - assertFalse(page.hotwordSearchEnablePref_.value); - - var control = page.$$('#hotwordSearchEnable'); - assertTrue(!!control); - assertFalse(control.disabled); - assertFalse(control.checked); - MockInteractions.tap(control.$.control); - Polymer.dom.flush(); - return browserProxy.whenCalled('setHotwordSearchEnabled'); - }).then(function() { - assertTrue(browserProxy.hotwordSearchEnabled); - }); - }); - - // Tests the UI when Hotword 'alwaysOn' is false. - test('HotwordNotAlwaysOn', function() { - return browserProxy.whenCalled('getSearchEnginesList').then(function() { - return browserProxy.whenCalled('getHotwordInfo'); - }).then(function() { - browserProxy.setHotwordInfo({ - allowed: true, - enabled: false, - alwaysOn: false, - errorMessage: '', - userName: '', - historyEnabled: false, - }); - Polymer.dom.flush(); - assertTrue(page.hotwordInfo_.allowed); - assertFalse(page.hotwordInfo_.alwaysOn); - assertFalse(page.hotwordInfo_.enabled); - - var control = page.$$('#hotwordSearchEnable'); - assertTrue(!!control); - assertFalse(control.disabled); - assertFalse(control.checked); - MockInteractions.tap(control.$.control); - Polymer.dom.flush(); - return browserProxy.whenCalled('setHotwordSearchEnabled'); - }).then(function() { - assertTrue(browserProxy.hotwordSearchEnabled); - }); - }); }); }); diff --git a/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js b/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js index ef6eb97f64202..cb72d567abbc0 100644 --- a/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js +++ b/chrome/test/data/webui/settings/test_search_engines_browser_proxy.js @@ -20,25 +20,10 @@ cr.define('settings_search', function() { 'searchEngineEditStarted', 'setDefaultSearchEngine', 'validateSearchEngineInput', - 'getHotwordInfo', - 'setHotwordSearchEnabled', ]); - /** @type {boolean} */ - this.hotwordSearchEnabled = false; - /** @private {!SearchEnginesInfo} */ this.searchEnginesInfo_ = {defaults: [], others: [], extensions: []}; - - /** @private {!SearchPageHotwordInfo} */ - this.hotwordInfo_ = { - allowed: true, - enabled: false, - alwaysOn: true, - errorMessage: '', - userName: 'user@test.org', - historyEnabled: false, - }; } /** @override */ @@ -78,20 +63,6 @@ cr.define('settings_search', function() { return Promise.resolve(true); } - /** @override */ - getHotwordInfo() { - this.methodCalled('getHotwordInfo'); - return Promise.resolve(this.hotwordInfo_); - } - - /** @override */ - setHotwordSearchEnabled(enabled) { - this.hotwordSearchEnabled = enabled; - this.hotwordInfo_.enabled = true; - this.hotwordInfo_.historyEnabled = this.hotwordInfo_.alwaysOn; - this.methodCalled('setHotwordSearchEnabled'); - } - /** * Sets the response to be returned by |getSearchEnginesList|. * @param {!SearchEnginesInfo} searchEnginesInfo @@ -100,14 +71,6 @@ cr.define('settings_search', function() { this.searchEnginesInfo_ = searchEnginesInfo; } - /** - * Sets the response to be returned by |getSearchEnginesList|. - * @param {!SearchPageHotwordInfo} hotwordInfo - */ - setHotwordInfo(hotwordInfo) { - this.hotwordInfo_ = hotwordInfo; - cr.webUIListenerCallback('hotword-info-update', this.hotwordInfo_); - } } /** diff --git a/extensions/common/api/_api_features.json b/extensions/common/api/_api_features.json index 605499b48bf4d..b20f47dcb1307 100644 --- a/extensions/common/api/_api_features.json +++ b/extensions/common/api/_api_features.json @@ -288,7 +288,6 @@ "3F65507A3B39259B38C8173C6FFA3D12DF64CCE9", // http://crbug.com/371562. "D7986543275120831B39EF28D1327552FC343960", // http://crbug.com/378067 "A291B26E088FA6BA53FFD72F0916F06EBA7C585A", // http://crbug.com/378067 - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // Hotword triggering "07BD6A765FFC289FF755D7CAB2893A40EC337FEC", // http://crbug.com/456214 "896B85CC7E913E11C34892C1425A093C0701D386", // http://crbug.com/456214 "11A01C82EF355E674E4F9728A801F5C3CB40D83F", // http://crbug.com/456214 diff --git a/extensions/common/api/_permission_features.json b/extensions/common/api/_permission_features.json index ccdddbeac470a..6e16e1815f919 100644 --- a/extensions/common/api/_permission_features.json +++ b/extensions/common/api/_permission_features.json @@ -116,8 +116,6 @@ "3F50C3A83839D9C76334BCE81CDEC06174F266AF", "39BE69F11F68E4EED080DA3DC2394F7885B7AFF9", "FF78670081967CE21DB86A04AD94A0498F01E20A", // http://crbug.com/409192 - // Hotword component extension - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", "0C0426C12F94156F330FFAF346A976BA8878DE78", // http://crbug.com/496954 "AC4538682FCECD28587C7A0F80849F78F4872BC2", // http://crbug.com/496954 "CCA4D85A67ADD65DA6C02E49EE3C080C54A8211C", // http://crbug.com/496954 @@ -380,7 +378,6 @@ "D2DAA9362153E8A5E3CF593E6DF4666421ABAD21", // http://crbug.com/374965 "D7986543275120831B39EF28D1327552FC343960", // http://crbug.com/378067 "A291B26E088FA6BA53FFD72F0916F06EBA7C585A", // http://crbug.com/378067 - "62CCAAD339E6451BBF97C4BBDF758E934A05AD0B", // Hotword triggering "07BD6A765FFC289FF755D7CAB2893A40EC337FEC", // http://crbug.com/456214 "896B85CC7E913E11C34892C1425A093C0701D386", // http://crbug.com/456214 "11A01C82EF355E674E4F9728A801F5C3CB40D83F", // http://crbug.com/456214 diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 9ce1eab9bb309..7c0e0cb209dff 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml @@ -5409,6 +5409,9 @@ should be able to be added at any place in this file. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org diff --git a/tools/metrics/actions/extract_actions.py b/tools/metrics/actions/extract_actions.py index 04d938d207a06..c572f7b0e553e 100755 --- a/tools/metrics/actions/extract_actions.py +++ b/tools/metrics/actions/extract_actions.py @@ -286,9 +286,6 @@ def AddExtensionActions(actions): actions.add('ConnectivityDiagnostics.UA.TestResultExpanded') actions.add('ConnectivityDiagnostics.UA.TestSuiteRun') - # Actions sent by 'Ok Google' Hotwording. - actions.add('Hotword.HotwordTrigger') - class InvalidStatementException(Exception): """Indicates an invalid statement was found.""" diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 36c7d2b8bb98d..c8e6625e65096 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml @@ -28244,6 +28244,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + rlp@chromium.org The state of the hotword audio logging preference. This value is emitted @@ -28254,6 +28257,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + rlp@chromium.org The state of the hotword preference. This value is emitted during @@ -28262,6 +28268,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + rlp@chromium.org Whether the external component hotword extension exists (i.e., not pending @@ -28272,6 +28281,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + rlp@chromium.org Errors reported by the hotword service when determining if hotwording is @@ -28282,6 +28294,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org @@ -28293,6 +28308,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org @@ -28305,6 +28323,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org @@ -28314,6 +28335,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org @@ -28324,6 +28348,9 @@ http://cs/file:chrome/histograms.xml - but prefer this file for new entries. + + Deprecated as of 10/2017. Feature removed with crbug/761426. + amistry@chromium.org rlp@chromium.org somast@chromium.org diff --git a/ui/app_list/speech_ui_model_observer.h b/ui/app_list/speech_ui_model_observer.h index 29ae46f1c160f..e4e2e7cde3d33 100644 --- a/ui/app_list/speech_ui_model_observer.h +++ b/ui/app_list/speech_ui_model_observer.h @@ -15,7 +15,6 @@ namespace app_list { enum SpeechRecognitionState { SPEECH_RECOGNITION_OFF = 0, SPEECH_RECOGNITION_READY, - SPEECH_RECOGNITION_HOTWORD_LISTENING, SPEECH_RECOGNITION_RECOGNIZING, SPEECH_RECOGNITION_IN_SPEECH, SPEECH_RECOGNITION_STOPPING, diff --git a/ui/app_list/views/search_box_view.cc b/ui/app_list/views/search_box_view.cc index 7fdd2912433fc..d25a23b971b0b 100644 --- a/ui/app_list/views/search_box_view.cc +++ b/ui/app_list/views/search_box_view.cc @@ -5,6 +5,8 @@ #include "ui/app_list/views/search_box_view.h" #include +#include +#include #include "ash/app_list/model/search_box_model.h" #include "base/macros.h" @@ -879,14 +881,7 @@ void SearchBoxView::SpeechRecognitionButtonPropChanged() { gfx::CreateVectorIcon(kIcMicBlackIcon, kMicIconSize, kDefaultSearchboxColor)); - // TODO(warx): consider removing on_tooltip as it is not accessible due to - // the overlap of speech UI. - if (view_delegate_->GetSpeechUI()->state() == - SPEECH_RECOGNITION_HOTWORD_LISTENING) { - speech_button_->SetTooltipText(speech_button_prop->on_tooltip); - } else { - speech_button_->SetTooltipText(speech_button_prop->off_tooltip); - } + speech_button_->SetTooltipText(speech_button_prop->tooltip); } else { if (speech_button_) { // Deleting a view will detach it from its parent.