Rename vector icon header files.
[chromium-blink-merge.git] / chrome / browser / search / hotword_service.cc
blobb2880b5493cd14c04fdd7f9eca6cee7fe741c0d6
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/search/hotword_service.h"
7 #include <string>
9 #include "base/command_line.h"
10 #include "base/i18n/case_conversion.h"
11 #include "base/location.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/extensions/pending_extension_manager.h"
25 #include "chrome/browser/extensions/updater/extension_updater.h"
26 #include "chrome/browser/notifications/notification.h"
27 #include "chrome/browser/notifications/notification_ui_manager.h"
28 #include "chrome/browser/plugins/plugin_prefs.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/profiles/profile_manager.h"
31 #include "chrome/browser/search/hotword_audio_history_handler.h"
32 #include "chrome/browser/search/hotword_service_factory.h"
33 #include "chrome/browser/ui/extensions/app_launch_params.h"
34 #include "chrome/browser/ui/extensions/application_launch.h"
35 #include "chrome/common/chrome_paths.h"
36 #include "chrome/common/chrome_switches.h"
37 #include "chrome/common/extensions/extension_constants.h"
38 #include "chrome/common/pref_names.h"
39 #include "chrome/grit/generated_resources.h"
40 #include "components/language_usage_metrics/language_usage_metrics.h"
41 #include "components/user_manager/user.h"
42 #include "components/user_manager/user_manager.h"
43 #include "content/public/browser/browser_thread.h"
44 #include "content/public/browser/notification_service.h"
45 #include "content/public/browser/plugin_service.h"
46 #include "content/public/common/webplugininfo.h"
47 #include "extensions/browser/extension_system.h"
48 #include "extensions/browser/uninstall_reason.h"
49 #include "extensions/common/constants.h"
50 #include "extensions/common/extension.h"
51 #include "extensions/common/one_shot_event.h"
52 #include "grit/theme_resources.h"
53 #include "ui/base/l10n/l10n_util.h"
54 #include "ui/base/resource/resource_bundle.h"
56 #if defined(OS_CHROMEOS)
57 #include "chromeos/audio/cras_audio_handler.h"
58 #endif
60 using extensions::BrowserContextKeyedAPIFactory;
61 using extensions::HotwordPrivateEventService;
63 namespace {
65 // Allowed locales for hotwording. Note that Chrome does not support all of
66 // these locales, condensing them to their 2-letter equivalent, but the full
67 // list is here for completeness and testing.
68 static const char* kSupportedLocales[] = {
69 "en",
70 "en_au",
71 "en_ca",
72 "en_gb",
73 "en_nz",
74 "en_us",
75 "en_za",
76 "de",
77 "de_at",
78 "de_de",
79 "es",
80 "es_419",
81 "es_es",
82 "fr",
83 "fr_fr",
84 "it",
85 "it_it",
86 "ja",
87 "ja_jp",
88 "ko",
89 "ko_kr",
90 "pt_br",
91 "ru",
92 "ru_ru"
95 // Maximum number of retries for installing the hotword shared module from the
96 // web store.
97 static const int kMaxInstallRetries = 2;
99 // Delay between retries for installing the hotword shared module from the web
100 // store.
101 static const int kInstallRetryDelaySeconds = 5;
103 // The extension id of the old hotword voice search trigger extension.
104 const char kHotwordOldExtensionId[] = "bepbmhgboaologfdajaanbcjmnhjmhfn";
106 // Enum describing the state of the hotword preference.
107 // This is used for UMA stats -- do not reorder or delete items; only add to
108 // the end.
109 enum HotwordEnabled {
110 UNSET = 0, // No hotword preference has been set.
111 ENABLED, // The (classic) hotword preference is enabled.
112 DISABLED, // All hotwording is disabled.
113 ALWAYS_ON_ENABLED, // Always-on hotwording is enabled.
114 NUM_HOTWORD_ENABLED_METRICS
117 // Enum describing the availability state of the hotword extension.
118 // This is used for UMA stats -- do not reorder or delete items; only add to
119 // the end.
120 enum HotwordExtensionAvailability {
121 UNAVAILABLE = 0,
122 AVAILABLE,
123 PENDING_DOWNLOAD,
124 DISABLED_EXTENSION,
125 NUM_HOTWORD_EXTENSION_AVAILABILITY_METRICS
128 // Enum describing the types of errors that can arise when determining
129 // if hotwording can be used. NO_ERROR is used so it can be seen how often
130 // errors arise relative to when they do not.
131 // This is used for UMA stats -- do not reorder or delete items; only add to
132 // the end.
133 enum HotwordError {
134 NO_HOTWORD_ERROR = 0,
135 GENERIC_HOTWORD_ERROR,
136 NACL_HOTWORD_ERROR,
137 MICROPHONE_HOTWORD_ERROR,
138 NUM_HOTWORD_ERROR_METRICS
141 void RecordLoggingMetrics(Profile* profile) {
142 // If the user is not opted in to hotword voice search, the audio logging
143 // metric is not valid so it is not recorded.
144 if (!profile->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled))
145 return;
147 UMA_HISTOGRAM_BOOLEAN(
148 "Hotword.HotwordAudioLogging",
149 profile->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled));
152 void RecordErrorMetrics(int error_message) {
153 HotwordError error = NO_HOTWORD_ERROR;
154 switch (error_message) {
155 case IDS_HOTWORD_GENERIC_ERROR_MESSAGE:
156 error = GENERIC_HOTWORD_ERROR;
157 break;
158 case IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE:
159 error = NACL_HOTWORD_ERROR;
160 break;
161 case IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE:
162 error = MICROPHONE_HOTWORD_ERROR;
163 break;
164 default:
165 error = NO_HOTWORD_ERROR;
168 UMA_HISTOGRAM_ENUMERATION("Hotword.HotwordError",
169 error,
170 NUM_HOTWORD_ERROR_METRICS);
173 void RecordHotwordEnabledMetric(HotwordService *service, Profile* profile) {
174 HotwordEnabled enabled_state = DISABLED;
175 auto prefs = profile->GetPrefs();
176 if (!prefs->HasPrefPath(prefs::kHotwordSearchEnabled) &&
177 !prefs->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled)) {
178 enabled_state = UNSET;
179 } else if (service->IsAlwaysOnEnabled()) {
180 enabled_state = ALWAYS_ON_ENABLED;
181 } else if (prefs->GetBoolean(prefs::kHotwordSearchEnabled)) {
182 enabled_state = ENABLED;
184 UMA_HISTOGRAM_ENUMERATION("Hotword.Enabled", enabled_state,
185 NUM_HOTWORD_ENABLED_METRICS);
188 ExtensionService* GetExtensionService(Profile* profile) {
189 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
191 extensions::ExtensionSystem* extension_system =
192 extensions::ExtensionSystem::Get(profile);
193 return extension_system ? extension_system->extension_service() : NULL;
196 std::string GetCurrentLocale(Profile* profile) {
197 #if defined(OS_CHROMEOS)
198 std::string profile_locale =
199 profile->GetPrefs()->GetString(prefs::kApplicationLocale);
200 if (!profile_locale.empty()) {
201 // On ChromeOS locale is per-profile, but only if set.
202 return profile_locale;
204 #endif
205 return g_browser_process->GetApplicationLocale();
208 } // namespace
210 namespace hotword_internal {
211 // String passed to indicate the training state has changed.
212 const char kHotwordTrainingEnabled[] = "hotword_training_enabled";
213 // Id of the hotword notification.
214 const char kHotwordNotificationId[] = "hotword";
215 // Notifier id for the hotword notification.
216 const char kHotwordNotifierId[] = "hotword.notification";
217 } // namespace hotword_internal
219 // Delegate for the hotword notification.
220 class HotwordNotificationDelegate : public NotificationDelegate {
221 public:
222 explicit HotwordNotificationDelegate(Profile* profile)
223 : profile_(profile) {
226 // Overridden from NotificationDelegate:
227 void ButtonClick(int button_index) override {
228 DCHECK_EQ(0, button_index);
229 Click();
232 void Click() override {
233 // Launch the hotword audio verification app in the right mode.
234 HotwordService::LaunchMode launch_mode =
235 HotwordService::HOTWORD_AND_AUDIO_HISTORY;
236 if (profile_->GetPrefs()->GetBoolean(
237 prefs::kHotwordAudioLoggingEnabled)) {
238 launch_mode = HotwordService::HOTWORD_ONLY;
241 HotwordService* hotword_service =
242 HotwordServiceFactory::GetForProfile(profile_);
244 if (!hotword_service)
245 return;
247 hotword_service->LaunchHotwordAudioVerificationApp(launch_mode);
249 // Close the notification after it's been clicked on to remove it
250 // from the notification tray.
251 g_browser_process->notification_ui_manager()->CancelById(
252 id(), NotificationUIManager::GetProfileID(profile_));
255 // Overridden from NotificationDelegate:
256 std::string id() const override {
257 return hotword_internal::kHotwordNotificationId;
260 private:
261 ~HotwordNotificationDelegate() override {}
263 Profile* profile_;
265 DISALLOW_COPY_AND_ASSIGN(HotwordNotificationDelegate);
268 // static
269 bool HotwordService::DoesHotwordSupportLanguage(Profile* profile) {
270 std::string normalized_locale =
271 base::ToLowerASCII(l10n_util::NormalizeLocale(GetCurrentLocale(profile)));
273 // For M43, we are limiting always-on to en_us only.
274 // TODO(kcarattini): Remove this once
275 // https://code.google.com/p/chrome-os-partner/issues/detail?id=39227
276 // is fixed.
277 if (HotwordServiceFactory::IsAlwaysOnAvailable())
278 return normalized_locale == "en_us";
280 for (size_t i = 0; i < arraysize(kSupportedLocales); i++) {
281 if (normalized_locale == kSupportedLocales[i])
282 return true;
284 return false;
287 // static
288 bool HotwordService::IsHotwordHardwareAvailable() {
289 #if defined(OS_CHROMEOS)
290 if (chromeos::CrasAudioHandler::IsInitialized()) {
291 chromeos::AudioDeviceList devices;
292 chromeos::CrasAudioHandler::Get()->GetAudioDevices(&devices);
293 for (size_t i = 0; i < devices.size(); ++i) {
294 if (devices[i].type == chromeos::AUDIO_TYPE_AOKR) {
295 DCHECK(devices[i].is_input);
296 return true;
300 #endif
301 return false;
304 #if defined(OS_CHROMEOS)
305 class HotwordService::HotwordUserSessionStateObserver
306 : public user_manager::UserManager::UserSessionStateObserver {
307 public:
308 explicit HotwordUserSessionStateObserver(HotwordService* service)
309 : service_(service) {}
311 // Overridden from UserSessionStateObserver:
312 void ActiveUserChanged(const user_manager::User* active_user) override {
313 service_->ActiveUserChanged();
316 private:
317 HotwordService* service_; // Not owned
319 #else
320 // Dummy class to please the linker.
321 class HotwordService::HotwordUserSessionStateObserver {
323 #endif
325 void HotwordService::HotwordWebstoreInstaller::Shutdown() {
326 AbortInstall();
329 HotwordService::HotwordService(Profile* profile)
330 : profile_(profile),
331 extension_registry_observer_(this),
332 microphone_available_(false),
333 audio_device_state_updated_(false),
334 client_(NULL),
335 error_message_(0),
336 reinstall_pending_(false),
337 training_(false),
338 weak_factory_(this) {
339 extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile));
341 // Disable the old extension so it doesn't interfere with the new stuff.
342 ExtensionService* extension_service = GetExtensionService(profile_);
343 if (extension_service) {
344 extension_service->DisableExtension(
345 kHotwordOldExtensionId,
346 extensions::Extension::DISABLE_USER_ACTION);
349 // This will be called during profile initialization which is a good time
350 // to check the user's hotword state.
351 RecordHotwordEnabledMetric(this, profile_);
353 pref_registrar_.Init(profile_->GetPrefs());
354 pref_registrar_.Add(
355 prefs::kHotwordAlwaysOnSearchEnabled,
356 base::Bind(&HotwordService::OnHotwordAlwaysOnSearchEnabledChanged,
357 base::Unretained(this)));
359 extensions::ExtensionSystem::Get(profile_)->ready().Post(
360 FROM_HERE,
361 base::Bind(base::IgnoreResult(
362 &HotwordService::MaybeReinstallHotwordExtension),
363 weak_factory_.GetWeakPtr()));
365 SetAudioHistoryHandler(new HotwordAudioHistoryHandler(
366 profile_, base::MessageLoop::current()->task_runner()));
368 if (HotwordServiceFactory::IsAlwaysOnAvailable() &&
369 IsHotwordAllowed()) {
370 // Show the hotword notification in 5 seconds if the experimental flag is
371 // on, or in 10 minutes if not. We need to wait at least a few seconds
372 // for the hotword extension to be installed.
373 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
374 if (command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware)) {
375 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
376 FROM_HERE, base::Bind(&HotwordService::ShowHotwordNotification,
377 weak_factory_.GetWeakPtr()),
378 base::TimeDelta::FromSeconds(5));
379 } else if (!profile_->GetPrefs()->GetBoolean(
380 prefs::kHotwordAlwaysOnNotificationSeen)) {
381 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
382 FROM_HERE, base::Bind(&HotwordService::ShowHotwordNotification,
383 weak_factory_.GetWeakPtr()),
384 base::TimeDelta::FromMinutes(10));
388 #if defined(OS_CHROMEOS)
389 if (user_manager::UserManager::IsInitialized()) {
390 session_observer_.reset(new HotwordUserSessionStateObserver(this));
391 user_manager::UserManager::Get()->AddSessionStateObserver(
392 session_observer_.get());
394 #endif
396 // Register with the device observer list to update the microphone
397 // availability.
398 content::BrowserThread::PostTask(
399 content::BrowserThread::UI, FROM_HERE,
400 base::Bind(&HotwordService::InitializeMicrophoneObserver,
401 base::Unretained(this)));
404 HotwordService::~HotwordService() {
405 #if defined(OS_CHROMEOS)
406 if (user_manager::UserManager::IsInitialized() && session_observer_) {
407 user_manager::UserManager::Get()->RemoveSessionStateObserver(
408 session_observer_.get());
410 #endif
413 void HotwordService::Shutdown() {
414 if (installer_.get())
415 installer_->Shutdown();
418 void HotwordService::ShowHotwordNotification() {
419 // Check for enabled here in case always-on was enabled during the delay.
420 if (!IsServiceAvailable() || IsAlwaysOnEnabled())
421 return;
423 message_center::RichNotificationData data;
424 const base::string16 label = l10n_util::GetStringUTF16(
425 IDS_HOTWORD_NOTIFICATION_BUTTON);
426 data.buttons.push_back(message_center::ButtonInfo(label));
428 Notification notification(
429 message_center::NOTIFICATION_TYPE_SIMPLE,
430 l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_TITLE),
431 l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_DESCRIPTION),
432 ui::ResourceBundle::GetSharedInstance().GetImageNamed(
433 IDR_HOTWORD_NOTIFICATION_ICON),
434 message_center::NotifierId(message_center::NotifierId::SYSTEM_COMPONENT,
435 hotword_internal::kHotwordNotifierId),
436 base::string16(), GURL(), std::string(), data,
437 new HotwordNotificationDelegate(profile_));
439 g_browser_process->notification_ui_manager()->Add(notification, profile_);
440 profile_->GetPrefs()->SetBoolean(
441 prefs::kHotwordAlwaysOnNotificationSeen, true);
444 void HotwordService::OnExtensionUninstalled(
445 content::BrowserContext* browser_context,
446 const extensions::Extension* extension,
447 extensions::UninstallReason reason) {
448 CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
450 if (extension->id() != extension_misc::kHotwordSharedModuleId ||
451 profile_ != Profile::FromBrowserContext(browser_context) ||
452 !GetExtensionService(profile_))
453 return;
455 // If the extension wasn't uninstalled due to language change, don't try to
456 // reinstall it.
457 if (!reinstall_pending_)
458 return;
460 InstallHotwordExtensionFromWebstore(kMaxInstallRetries);
461 SetPreviousLanguagePref();
464 std::string HotwordService::ReinstalledExtensionId() {
465 return extension_misc::kHotwordSharedModuleId;
468 void HotwordService::InitializeMicrophoneObserver() {
469 MediaCaptureDevicesDispatcher::GetInstance()->AddObserver(this);
472 void HotwordService::InstalledFromWebstoreCallback(
473 int num_tries,
474 bool success,
475 const std::string& error,
476 extensions::webstore_install::Result result) {
477 if (result != extensions::webstore_install::SUCCESS && num_tries) {
478 // Try again on failure.
479 content::BrowserThread::PostDelayedTask(
480 content::BrowserThread::UI,
481 FROM_HERE,
482 base::Bind(&HotwordService::InstallHotwordExtensionFromWebstore,
483 weak_factory_.GetWeakPtr(),
484 num_tries),
485 base::TimeDelta::FromSeconds(kInstallRetryDelaySeconds));
489 void HotwordService::InstallHotwordExtensionFromWebstore(int num_tries) {
490 installer_ = new HotwordWebstoreInstaller(
491 ReinstalledExtensionId(),
492 profile_,
493 base::Bind(&HotwordService::InstalledFromWebstoreCallback,
494 weak_factory_.GetWeakPtr(),
495 num_tries - 1));
496 installer_->BeginInstall();
499 void HotwordService::OnExtensionInstalled(
500 content::BrowserContext* browser_context,
501 const extensions::Extension* extension,
502 bool is_update) {
504 if (extension->id() != extension_misc::kHotwordSharedModuleId ||
505 profile_ != Profile::FromBrowserContext(browser_context))
506 return;
508 // If the previous locale pref has never been set, set it now since
509 // the extension has been installed.
510 if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage))
511 SetPreviousLanguagePref();
513 // If MaybeReinstallHotwordExtension already triggered an uninstall, we
514 // don't want to loop and trigger another uninstall-install cycle.
515 // However, if we arrived here via an uninstall-triggered-install (and in
516 // that case |reinstall_pending_| will be true) then we know install
517 // has completed and we can reset |reinstall_pending_|.
518 if (!reinstall_pending_)
519 MaybeReinstallHotwordExtension();
520 else
521 reinstall_pending_ = false;
524 bool HotwordService::MaybeReinstallHotwordExtension() {
525 CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
527 ExtensionService* extension_service = GetExtensionService(profile_);
528 if (!extension_service)
529 return false;
531 const extensions::Extension* extension = extension_service->GetExtensionById(
532 ReinstalledExtensionId(), true);
533 if (!extension)
534 return false;
536 // If the extension is currently pending, return and we'll check again
537 // after the install is finished.
538 extensions::PendingExtensionManager* pending_manager =
539 extension_service->pending_extension_manager();
540 if (pending_manager->IsIdPending(extension->id()))
541 return false;
543 // If there is already a pending request from HotwordService, don't try
544 // to uninstall either.
545 if (reinstall_pending_)
546 return false;
548 // Check if the current locale matches the previous. If they don't match,
549 // uninstall the extension.
550 if (!ShouldReinstallHotwordExtension())
551 return false;
553 // Ensure the call to OnExtensionUninstalled was triggered by a language
554 // change so it's okay to reinstall.
555 reinstall_pending_ = true;
557 // Disable always-on on a language change. We do this because the speaker-id
558 // model needs to be re-trained.
559 if (IsAlwaysOnEnabled()) {
560 profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled,
561 false);
564 // Record re-installs due to language change.
565 UMA_HISTOGRAM_SPARSE_SLOWLY(
566 "Hotword.SharedModuleReinstallLanguage",
567 language_usage_metrics::LanguageUsageMetrics::ToLanguageCode(
568 GetCurrentLocale(profile_)));
569 return UninstallHotwordExtension(extension_service);
572 bool HotwordService::UninstallHotwordExtension(
573 ExtensionService* extension_service) {
574 base::string16 error;
575 std::string extension_id = ReinstalledExtensionId();
576 if (!extension_service->UninstallExtension(
577 extension_id,
578 extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT,
579 base::Bind(&base::DoNothing),
580 &error)) {
581 LOG(WARNING) << "Cannot uninstall extension with id "
582 << extension_id
583 << ": " << error;
584 reinstall_pending_ = false;
585 return false;
587 return true;
590 bool HotwordService::IsServiceAvailable() {
591 error_message_ = 0;
593 // Determine if the extension is available.
594 extensions::ExtensionSystem* system =
595 extensions::ExtensionSystem::Get(profile_);
596 ExtensionService* service = system->extension_service();
597 // Include disabled extensions (true parameter) since it may not be enabled
598 // if the user opted out.
599 const extensions::Extension* extension =
600 service->GetExtensionById(ReinstalledExtensionId(), true);
601 if (!extension)
602 error_message_ = IDS_HOTWORD_GENERIC_ERROR_MESSAGE;
604 // TODO(amistry): Record availability of shared module in UMA.
605 RecordLoggingMetrics(profile_);
607 // Determine if NaCl is available.
608 bool nacl_enabled = false;
609 base::FilePath path;
610 if (PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) {
611 content::WebPluginInfo info;
612 PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_).get();
613 if (content::PluginService::GetInstance()->GetPluginInfoByPath(path, &info))
614 nacl_enabled = plugin_prefs->IsPluginEnabled(info);
616 if (!nacl_enabled)
617 error_message_ = IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE;
619 RecordErrorMetrics(error_message_);
621 // Determine if the proper audio capabilities exist. The first time this is
622 // called, it probably won't return in time, but that's why it won't be
623 // included in the error calculation. However, this use case is rare and
624 // typically the devices will be initialized by the time a user goes to
625 // settings.
626 HotwordServiceFactory::GetInstance()->UpdateMicrophoneState();
627 if (audio_device_state_updated_) {
628 bool audio_capture_allowed =
629 profile_->GetPrefs()->GetBoolean(prefs::kAudioCaptureAllowed);
630 if (!audio_capture_allowed || !microphone_available_)
631 error_message_ = IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE;
634 return (error_message_ == 0) && IsHotwordAllowed();
637 bool HotwordService::IsHotwordAllowed() {
638 #if defined(ENABLE_HOTWORDING)
639 return DoesHotwordSupportLanguage(profile_);
640 #else
641 return false;
642 #endif
645 bool HotwordService::IsOptedIntoAudioLogging() {
646 // Do not opt the user in if the preference has not been set.
647 return
648 profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAudioLoggingEnabled) &&
649 profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled);
652 bool HotwordService::IsAlwaysOnEnabled() {
653 return
654 profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled) &&
655 profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled) &&
656 HotwordServiceFactory::IsAlwaysOnAvailable();
659 bool HotwordService::IsSometimesOnEnabled() {
660 return profile_->GetPrefs()->HasPrefPath(prefs::kHotwordSearchEnabled) &&
661 profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled) &&
662 !HotwordServiceFactory::IsAlwaysOnAvailable();
665 void HotwordService::SpeakerModelExistsComplete(bool exists) {
666 if (exists) {
667 profile_->GetPrefs()->
668 SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true);
669 } else {
670 LaunchHotwordAudioVerificationApp(HotwordService::HOTWORD_ONLY);
674 void HotwordService::OptIntoHotwording(
675 const LaunchMode& launch_mode) {
676 // If the notification is in the notification tray, remove it (since the user
677 // is manually opting in to hotwording, they do not need the promotion).
678 g_browser_process->notification_ui_manager()->CancelById(
679 hotword_internal::kHotwordNotificationId,
680 NotificationUIManager::GetProfileID(profile_));
682 // First determine if we actually need to launch the app, or can just enable
683 // the pref. If Audio History has already been enabled, and we already have
684 // a speaker model, then we don't need to launch the app at all.
685 if (launch_mode == HotwordService::HOTWORD_ONLY) {
686 HotwordPrivateEventService* event_service =
687 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(
688 profile_);
689 if (event_service) {
690 event_service->OnSpeakerModelExists();
691 return;
695 LaunchHotwordAudioVerificationApp(launch_mode);
698 void HotwordService::LaunchHotwordAudioVerificationApp(
699 const LaunchMode& launch_mode) {
700 hotword_audio_verification_launch_mode_ = launch_mode;
702 ExtensionService* extension_service = GetExtensionService(profile_);
703 if (!extension_service)
704 return;
705 const extensions::Extension* extension = extension_service->GetExtensionById(
706 extension_misc::kHotwordAudioVerificationAppId, true);
707 if (!extension)
708 return;
710 OpenApplication(
711 AppLaunchParams(profile_, extension, extensions::LAUNCH_CONTAINER_WINDOW,
712 NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL));
715 HotwordService::LaunchMode
716 HotwordService::GetHotwordAudioVerificationLaunchMode() {
717 return hotword_audio_verification_launch_mode_;
720 void HotwordService::StartTraining() {
721 training_ = true;
723 if (!IsServiceAvailable())
724 return;
726 HotwordPrivateEventService* event_service =
727 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
728 if (event_service)
729 event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled);
732 void HotwordService::FinalizeSpeakerModel() {
733 if (!IsServiceAvailable())
734 return;
736 HotwordPrivateEventService* event_service =
737 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
738 if (event_service)
739 event_service->OnFinalizeSpeakerModel();
742 void HotwordService::StopTraining() {
743 training_ = false;
745 if (!IsServiceAvailable())
746 return;
748 HotwordPrivateEventService* event_service =
749 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
750 if (event_service)
751 event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled);
754 void HotwordService::NotifyHotwordTriggered() {
755 if (!IsServiceAvailable())
756 return;
758 HotwordPrivateEventService* event_service =
759 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
760 if (event_service)
761 event_service->OnHotwordTriggered();
764 bool HotwordService::IsTraining() {
765 return training_;
768 HotwordAudioHistoryHandler* HotwordService::GetAudioHistoryHandler() {
769 return audio_history_handler_.get();
772 void HotwordService::SetAudioHistoryHandler(
773 HotwordAudioHistoryHandler* handler) {
774 audio_history_handler_.reset(handler);
775 audio_history_handler_->UpdateAudioHistoryState();
778 void HotwordService::DisableHotwordPreferences() {
779 if (IsSometimesOnEnabled()) {
780 profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false);
782 if (IsAlwaysOnEnabled()) {
783 profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled,
784 false);
788 void HotwordService::OnUpdateAudioDevices(
789 const content::MediaStreamDevices& devices) {
790 bool microphone_was_available = microphone_available_;
791 microphone_available_ = !devices.empty();
792 audio_device_state_updated_ = true;
793 HotwordPrivateEventService* event_service =
794 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
795 if (event_service && microphone_was_available != microphone_available_)
796 event_service->OnMicrophoneStateChanged(microphone_available_);
799 void HotwordService::OnHotwordAlwaysOnSearchEnabledChanged(
800 const std::string& pref_name) {
801 // If the pref for always on has been changed in some way, that means that
802 // the user is aware of always on (either from settings or another source)
803 // so they don't need to be shown the notification.
804 profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnNotificationSeen,
805 true);
806 pref_registrar_.Remove(prefs::kHotwordAlwaysOnSearchEnabled);
809 void HotwordService::RequestHotwordSession(HotwordClient* client) {
810 if (!IsServiceAvailable() || (client_ && client_ != client))
811 return;
813 client_ = client;
815 HotwordPrivateEventService* event_service =
816 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
817 if (event_service)
818 event_service->OnHotwordSessionRequested();
821 void HotwordService::StopHotwordSession(HotwordClient* client) {
822 if (!IsServiceAvailable())
823 return;
825 // Do nothing if there's no client.
826 if (!client_)
827 return;
828 DCHECK(client_ == client);
830 client_ = NULL;
831 HotwordPrivateEventService* event_service =
832 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
833 if (event_service)
834 event_service->OnHotwordSessionStopped();
837 void HotwordService::SetPreviousLanguagePref() {
838 profile_->GetPrefs()->SetString(prefs::kHotwordPreviousLanguage,
839 GetCurrentLocale(profile_));
842 bool HotwordService::ShouldReinstallHotwordExtension() {
843 // If there is no previous locale pref, then this is the first install
844 // so no need to uninstall first.
845 if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage))
846 return false;
848 std::string previous_locale =
849 profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage);
850 std::string locale = GetCurrentLocale(profile_);
852 // If it's a new locale, then the old extension should be uninstalled.
853 return locale != previous_locale &&
854 HotwordService::DoesHotwordSupportLanguage(profile_);
857 void HotwordService::ActiveUserChanged() {
858 // Don't bother notifying the extension if hotwording is completely off.
859 if (!IsSometimesOnEnabled() && !IsAlwaysOnEnabled() && !IsTraining())
860 return;
862 HotwordPrivateEventService* event_service =
863 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
864 // "enabled" isn't being changed, but piggy-back off the notification anyway.
865 if (event_service)
866 event_service->OnEnabledChanged(prefs::kHotwordSearchEnabled);
869 bool HotwordService::UserIsActive() {
870 #if defined(OS_CHROMEOS)
871 // Only support multiple profiles and profile switching in ChromeOS.
872 if (user_manager::UserManager::IsInitialized()) {
873 user_manager::User* user =
874 user_manager::UserManager::Get()->GetActiveUser();
875 if (user && user->is_profile_created())
876 return profile_ == ProfileManager::GetActiveUserProfile();
878 #endif
879 return true;