Make castv2 performance test work.
[chromium-blink-merge.git] / chrome / browser / search / hotword_service.cc
blobdb9d85faa3bde9292d20191cc704ce296d722528
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/message_loop/message_loop.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/sparse_histogram.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_service.h"
17 #include "chrome/browser/browser_process.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/extensions/api/hotword_private/hotword_private_api.h"
20 #include "chrome/browser/extensions/extension_service.h"
21 #include "chrome/browser/extensions/pending_extension_manager.h"
22 #include "chrome/browser/extensions/updater/extension_updater.h"
23 #include "chrome/browser/notifications/notification.h"
24 #include "chrome/browser/notifications/notification_ui_manager.h"
25 #include "chrome/browser/plugins/plugin_prefs.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/profiles/profile_manager.h"
28 #include "chrome/browser/search/hotword_audio_history_handler.h"
29 #include "chrome/browser/search/hotword_service_factory.h"
30 #include "chrome/browser/ui/extensions/app_launch_params.h"
31 #include "chrome/browser/ui/extensions/application_launch.h"
32 #include "chrome/common/chrome_paths.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/extensions/extension_constants.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/grit/generated_resources.h"
37 #include "components/language_usage_metrics/language_usage_metrics.h"
38 #include "components/user_manager/user.h"
39 #include "components/user_manager/user_manager.h"
40 #include "content/public/browser/browser_thread.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/plugin_service.h"
43 #include "content/public/common/webplugininfo.h"
44 #include "extensions/browser/extension_system.h"
45 #include "extensions/browser/uninstall_reason.h"
46 #include "extensions/common/constants.h"
47 #include "extensions/common/extension.h"
48 #include "extensions/common/one_shot_event.h"
49 #include "grit/theme_resources.h"
50 #include "ui/base/l10n/l10n_util.h"
51 #include "ui/base/resource/resource_bundle.h"
53 #if defined(OS_CHROMEOS)
54 #include "chromeos/audio/cras_audio_handler.h"
55 #endif
57 using extensions::BrowserContextKeyedAPIFactory;
58 using extensions::HotwordPrivateEventService;
60 namespace {
62 // Allowed locales for hotwording. Note that Chrome does not support all of
63 // these locales, condensing them to their 2-letter equivalent, but the full
64 // list is here for completeness and testing.
65 static const char* kSupportedLocales[] = {
66 "en",
67 "en_au",
68 "en_ca",
69 "en_gb",
70 "en_nz",
71 "en_us",
72 "en_za",
73 "de",
74 "de_at",
75 "de_de",
76 "es",
77 "es_419",
78 "es_es",
79 "fr",
80 "fr_fr",
81 "it",
82 "it_it",
83 "ja",
84 "ja_jp",
85 "ko",
86 "ko_kr",
87 "pt_br",
88 "ru",
89 "ru_ru"
92 // Maximum number of retries for installing the hotword shared module from the
93 // web store.
94 static const int kMaxInstallRetries = 2;
96 // Delay between retries for installing the hotword shared module from the web
97 // store.
98 static const int kInstallRetryDelaySeconds = 5;
100 // The extension id of the old hotword voice search trigger extension.
101 const char kHotwordOldExtensionId[] = "bepbmhgboaologfdajaanbcjmnhjmhfn";
103 // Enum describing the state of the hotword preference.
104 // This is used for UMA stats -- do not reorder or delete items; only add to
105 // the end.
106 enum HotwordEnabled {
107 UNSET = 0, // No hotword preference has been set.
108 ENABLED, // The (classic) hotword preference is enabled.
109 DISABLED, // All hotwording is disabled.
110 ALWAYS_ON_ENABLED, // Always-on hotwording is enabled.
111 NUM_HOTWORD_ENABLED_METRICS
114 // Enum describing the availability state of the hotword extension.
115 // This is used for UMA stats -- do not reorder or delete items; only add to
116 // the end.
117 enum HotwordExtensionAvailability {
118 UNAVAILABLE = 0,
119 AVAILABLE,
120 PENDING_DOWNLOAD,
121 DISABLED_EXTENSION,
122 NUM_HOTWORD_EXTENSION_AVAILABILITY_METRICS
125 // Enum describing the types of errors that can arise when determining
126 // if hotwording can be used. NO_ERROR is used so it can be seen how often
127 // errors arise relative to when they do not.
128 // This is used for UMA stats -- do not reorder or delete items; only add to
129 // the end.
130 enum HotwordError {
131 NO_HOTWORD_ERROR = 0,
132 GENERIC_HOTWORD_ERROR,
133 NACL_HOTWORD_ERROR,
134 MICROPHONE_HOTWORD_ERROR,
135 NUM_HOTWORD_ERROR_METRICS
138 void RecordLoggingMetrics(Profile* profile) {
139 // If the user is not opted in to hotword voice search, the audio logging
140 // metric is not valid so it is not recorded.
141 if (!profile->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled))
142 return;
144 UMA_HISTOGRAM_BOOLEAN(
145 "Hotword.HotwordAudioLogging",
146 profile->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled));
149 void RecordErrorMetrics(int error_message) {
150 HotwordError error = NO_HOTWORD_ERROR;
151 switch (error_message) {
152 case IDS_HOTWORD_GENERIC_ERROR_MESSAGE:
153 error = GENERIC_HOTWORD_ERROR;
154 break;
155 case IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE:
156 error = NACL_HOTWORD_ERROR;
157 break;
158 case IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE:
159 error = MICROPHONE_HOTWORD_ERROR;
160 break;
161 default:
162 error = NO_HOTWORD_ERROR;
165 UMA_HISTOGRAM_ENUMERATION("Hotword.HotwordError",
166 error,
167 NUM_HOTWORD_ERROR_METRICS);
170 void RecordHotwordEnabledMetric(HotwordService *service, Profile* profile) {
171 HotwordEnabled enabled_state = DISABLED;
172 auto prefs = profile->GetPrefs();
173 if (!prefs->HasPrefPath(prefs::kHotwordSearchEnabled) &&
174 !prefs->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled)) {
175 enabled_state = UNSET;
176 } else if (service->IsAlwaysOnEnabled()) {
177 enabled_state = ALWAYS_ON_ENABLED;
178 } else if (prefs->GetBoolean(prefs::kHotwordSearchEnabled)) {
179 enabled_state = ENABLED;
181 UMA_HISTOGRAM_ENUMERATION("Hotword.Enabled", enabled_state,
182 NUM_HOTWORD_ENABLED_METRICS);
185 ExtensionService* GetExtensionService(Profile* profile) {
186 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
188 extensions::ExtensionSystem* extension_system =
189 extensions::ExtensionSystem::Get(profile);
190 return extension_system ? extension_system->extension_service() : NULL;
193 std::string GetCurrentLocale(Profile* profile) {
194 #if defined(OS_CHROMEOS)
195 std::string profile_locale =
196 profile->GetPrefs()->GetString(prefs::kApplicationLocale);
197 if (!profile_locale.empty()) {
198 // On ChromeOS locale is per-profile, but only if set.
199 return profile_locale;
201 #endif
202 return g_browser_process->GetApplicationLocale();
205 } // namespace
207 namespace hotword_internal {
208 // Constants for the hotword field trial.
209 const char kHotwordFieldTrialName[] = "VoiceTrigger";
210 const char kHotwordFieldTrialDisabledGroupName[] = "Disabled";
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 l10n_util::NormalizeLocale(GetCurrentLocale(profile));
272 base::StringToLowerASCII(&normalized_locale);
274 for (size_t i = 0; i < arraysize(kSupportedLocales); i++) {
275 if (normalized_locale == kSupportedLocales[i])
276 return true;
278 return false;
281 // static
282 bool HotwordService::IsHotwordHardwareAvailable() {
283 #if defined(OS_CHROMEOS)
284 if (chromeos::CrasAudioHandler::IsInitialized()) {
285 chromeos::AudioDeviceList devices;
286 chromeos::CrasAudioHandler::Get()->GetAudioDevices(&devices);
287 for (size_t i = 0; i < devices.size(); ++i) {
288 if (devices[i].type == chromeos::AUDIO_TYPE_AOKR) {
289 DCHECK(devices[i].is_input);
290 return true;
294 #endif
295 return false;
298 #if defined(OS_CHROMEOS)
299 class HotwordService::HotwordUserSessionStateObserver
300 : public user_manager::UserManager::UserSessionStateObserver {
301 public:
302 explicit HotwordUserSessionStateObserver(HotwordService* service)
303 : service_(service) {}
305 // Overridden from UserSessionStateObserver:
306 void ActiveUserChanged(const user_manager::User* active_user) override {
307 service_->ActiveUserChanged();
310 private:
311 HotwordService* service_; // Not owned
313 #else
314 // Dummy class to please the linker.
315 class HotwordService::HotwordUserSessionStateObserver {
317 #endif
319 void HotwordService::HotwordWebstoreInstaller::Shutdown() {
320 AbortInstall();
323 HotwordService::HotwordService(Profile* profile)
324 : profile_(profile),
325 extension_registry_observer_(this),
326 microphone_available_(false),
327 audio_device_state_updated_(false),
328 client_(NULL),
329 error_message_(0),
330 reinstall_pending_(false),
331 training_(false),
332 weak_factory_(this) {
333 extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile));
335 // Disable the old extension so it doesn't interfere with the new stuff.
336 ExtensionService* extension_service = GetExtensionService(profile_);
337 if (extension_service) {
338 extension_service->DisableExtension(
339 kHotwordOldExtensionId,
340 extensions::Extension::DISABLE_USER_ACTION);
343 // This will be called during profile initialization which is a good time
344 // to check the user's hotword state.
345 RecordHotwordEnabledMetric(this, profile_);
347 pref_registrar_.Init(profile_->GetPrefs());
348 pref_registrar_.Add(
349 prefs::kHotwordAlwaysOnSearchEnabled,
350 base::Bind(&HotwordService::OnHotwordAlwaysOnSearchEnabledChanged,
351 base::Unretained(this)));
353 extensions::ExtensionSystem::Get(profile_)->ready().Post(
354 FROM_HERE,
355 base::Bind(base::IgnoreResult(
356 &HotwordService::MaybeReinstallHotwordExtension),
357 weak_factory_.GetWeakPtr()));
359 SetAudioHistoryHandler(new HotwordAudioHistoryHandler(
360 profile_, base::MessageLoop::current()->task_runner()));
362 if (HotwordServiceFactory::IsAlwaysOnAvailable() &&
363 IsHotwordAllowed()) {
364 // Show the hotword notification in 5 seconds if the experimental flag is
365 // on, or in 10 minutes if not. We need to wait at least a few seconds
366 // for the hotword extension to be installed.
367 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
368 if (command_line->HasSwitch(switches::kEnableExperimentalHotwordHardware)) {
369 base::MessageLoop::current()->PostDelayedTask(
370 FROM_HERE,
371 base::Bind(&HotwordService::ShowHotwordNotification,
372 weak_factory_.GetWeakPtr()),
373 base::TimeDelta::FromSeconds(5));
374 } else if (!profile_->GetPrefs()->GetBoolean(
375 prefs::kHotwordAlwaysOnNotificationSeen)) {
376 base::MessageLoop::current()->PostDelayedTask(
377 FROM_HERE,
378 base::Bind(&HotwordService::ShowHotwordNotification,
379 weak_factory_.GetWeakPtr()),
380 base::TimeDelta::FromMinutes(10));
384 #if defined(OS_CHROMEOS)
385 if (user_manager::UserManager::IsInitialized()) {
386 session_observer_.reset(new HotwordUserSessionStateObserver(this));
387 user_manager::UserManager::Get()->AddSessionStateObserver(
388 session_observer_.get());
390 #endif
392 // Register with the device observer list to update the microphone
393 // availability.
394 content::BrowserThread::PostTask(
395 content::BrowserThread::UI, FROM_HERE,
396 base::Bind(&HotwordService::InitializeMicrophoneObserver,
397 base::Unretained(this)));
400 HotwordService::~HotwordService() {
401 #if defined(OS_CHROMEOS)
402 if (user_manager::UserManager::IsInitialized() && session_observer_) {
403 user_manager::UserManager::Get()->RemoveSessionStateObserver(
404 session_observer_.get());
406 #endif
409 void HotwordService::Shutdown() {
410 if (installer_.get())
411 installer_->Shutdown();
414 void HotwordService::ShowHotwordNotification() {
415 // Check for enabled here in case always-on was enabled during the delay.
416 if (!IsServiceAvailable() || IsAlwaysOnEnabled())
417 return;
419 message_center::RichNotificationData data;
420 const base::string16 label = l10n_util::GetStringUTF16(
421 IDS_HOTWORD_NOTIFICATION_BUTTON);
422 data.buttons.push_back(message_center::ButtonInfo(label));
424 Notification notification(
425 message_center::NOTIFICATION_TYPE_SIMPLE,
426 GURL(),
427 l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_TITLE),
428 l10n_util::GetStringUTF16(IDS_HOTWORD_NOTIFICATION_DESCRIPTION),
429 ui::ResourceBundle::GetSharedInstance().GetImageNamed(
430 IDR_HOTWORD_NOTIFICATION_ICON),
431 message_center::NotifierId(
432 message_center::NotifierId::SYSTEM_COMPONENT,
433 hotword_internal::kHotwordNotifierId),
434 base::string16(),
435 std::string(),
436 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 std::string group = base::FieldTrialList::FindFullName(
639 hotword_internal::kHotwordFieldTrialName);
640 // Allow hotwording by default, and only disable if the field trial has been
641 // set.
642 if (group == hotword_internal::kHotwordFieldTrialDisabledGroupName)
643 return false;
645 return DoesHotwordSupportLanguage(profile_);
648 bool HotwordService::IsOptedIntoAudioLogging() {
649 // Do not opt the user in if the preference has not been set.
650 return
651 profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAudioLoggingEnabled) &&
652 profile_->GetPrefs()->GetBoolean(prefs::kHotwordAudioLoggingEnabled);
655 bool HotwordService::IsAlwaysOnEnabled() {
656 return
657 profile_->GetPrefs()->HasPrefPath(prefs::kHotwordAlwaysOnSearchEnabled) &&
658 profile_->GetPrefs()->GetBoolean(prefs::kHotwordAlwaysOnSearchEnabled) &&
659 HotwordServiceFactory::IsAlwaysOnAvailable();
662 bool HotwordService::IsSometimesOnEnabled() {
663 return profile_->GetPrefs()->HasPrefPath(prefs::kHotwordSearchEnabled) &&
664 profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled) &&
665 !HotwordServiceFactory::IsAlwaysOnAvailable();
668 void HotwordService::SpeakerModelExistsComplete(bool exists) {
669 if (exists) {
670 profile_->GetPrefs()->
671 SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled, true);
672 } else {
673 LaunchHotwordAudioVerificationApp(HotwordService::HOTWORD_ONLY);
677 void HotwordService::OptIntoHotwording(
678 const LaunchMode& launch_mode) {
679 // First determine if we actually need to launch the app, or can just enable
680 // the pref. If Audio History has already been enabled, and we already have
681 // a speaker model, then we don't need to launch the app at all.
682 if (launch_mode == HotwordService::HOTWORD_ONLY) {
683 HotwordPrivateEventService* event_service =
684 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(
685 profile_);
686 if (event_service) {
687 event_service->OnSpeakerModelExists();
688 return;
692 LaunchHotwordAudioVerificationApp(launch_mode);
695 void HotwordService::LaunchHotwordAudioVerificationApp(
696 const LaunchMode& launch_mode) {
697 hotword_audio_verification_launch_mode_ = launch_mode;
699 ExtensionService* extension_service = GetExtensionService(profile_);
700 if (!extension_service)
701 return;
702 const extensions::Extension* extension = extension_service->GetExtensionById(
703 extension_misc::kHotwordAudioVerificationAppId, true);
704 if (!extension)
705 return;
707 OpenApplication(
708 AppLaunchParams(profile_, extension, extensions::LAUNCH_CONTAINER_WINDOW,
709 NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL));
712 HotwordService::LaunchMode
713 HotwordService::GetHotwordAudioVerificationLaunchMode() {
714 return hotword_audio_verification_launch_mode_;
717 void HotwordService::StartTraining() {
718 training_ = true;
720 if (!IsServiceAvailable())
721 return;
723 HotwordPrivateEventService* event_service =
724 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
725 if (event_service)
726 event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled);
729 void HotwordService::FinalizeSpeakerModel() {
730 if (!IsServiceAvailable())
731 return;
733 HotwordPrivateEventService* event_service =
734 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
735 if (event_service)
736 event_service->OnFinalizeSpeakerModel();
739 void HotwordService::StopTraining() {
740 training_ = false;
742 if (!IsServiceAvailable())
743 return;
745 HotwordPrivateEventService* event_service =
746 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
747 if (event_service)
748 event_service->OnEnabledChanged(hotword_internal::kHotwordTrainingEnabled);
751 void HotwordService::NotifyHotwordTriggered() {
752 if (!IsServiceAvailable())
753 return;
755 HotwordPrivateEventService* event_service =
756 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
757 if (event_service)
758 event_service->OnHotwordTriggered();
761 bool HotwordService::IsTraining() {
762 return training_;
765 HotwordAudioHistoryHandler* HotwordService::GetAudioHistoryHandler() {
766 return audio_history_handler_.get();
769 void HotwordService::SetAudioHistoryHandler(
770 HotwordAudioHistoryHandler* handler) {
771 audio_history_handler_.reset(handler);
772 audio_history_handler_->UpdateAudioHistoryState();
775 void HotwordService::DisableHotwordPreferences() {
776 if (IsSometimesOnEnabled()) {
777 profile_->GetPrefs()->SetBoolean(prefs::kHotwordSearchEnabled, false);
779 if (IsAlwaysOnEnabled()) {
780 profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnSearchEnabled,
781 false);
785 void HotwordService::OnUpdateAudioDevices(
786 const content::MediaStreamDevices& devices) {
787 bool microphone_was_available = microphone_available_;
788 microphone_available_ = !devices.empty();
789 audio_device_state_updated_ = true;
790 HotwordPrivateEventService* event_service =
791 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
792 if (event_service && microphone_was_available != microphone_available_)
793 event_service->OnMicrophoneStateChanged(microphone_available_);
796 void HotwordService::OnHotwordAlwaysOnSearchEnabledChanged(
797 const std::string& pref_name) {
798 // If the pref for always on has been changed in some way, that means that
799 // the user is aware of always on (either from settings or another source)
800 // so they don't need to be shown the notification.
801 profile_->GetPrefs()->SetBoolean(prefs::kHotwordAlwaysOnNotificationSeen,
802 true);
803 pref_registrar_.Remove(prefs::kHotwordAlwaysOnSearchEnabled);
806 void HotwordService::RequestHotwordSession(HotwordClient* client) {
807 if (!IsServiceAvailable() || (client_ && client_ != client))
808 return;
810 client_ = client;
812 HotwordPrivateEventService* event_service =
813 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
814 if (event_service)
815 event_service->OnHotwordSessionRequested();
818 void HotwordService::StopHotwordSession(HotwordClient* client) {
819 if (!IsServiceAvailable())
820 return;
822 // Do nothing if there's no client.
823 if (!client_)
824 return;
825 DCHECK(client_ == client);
827 client_ = NULL;
828 HotwordPrivateEventService* event_service =
829 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
830 if (event_service)
831 event_service->OnHotwordSessionStopped();
834 void HotwordService::SetPreviousLanguagePref() {
835 profile_->GetPrefs()->SetString(prefs::kHotwordPreviousLanguage,
836 GetCurrentLocale(profile_));
839 bool HotwordService::ShouldReinstallHotwordExtension() {
840 // If there is no previous locale pref, then this is the first install
841 // so no need to uninstall first.
842 if (!profile_->GetPrefs()->HasPrefPath(prefs::kHotwordPreviousLanguage))
843 return false;
845 std::string previous_locale =
846 profile_->GetPrefs()->GetString(prefs::kHotwordPreviousLanguage);
847 std::string locale = GetCurrentLocale(profile_);
849 // If it's a new locale, then the old extension should be uninstalled.
850 return locale != previous_locale &&
851 HotwordService::DoesHotwordSupportLanguage(profile_);
854 void HotwordService::ActiveUserChanged() {
855 // Don't bother notifying the extension if hotwording is completely off.
856 if (!IsSometimesOnEnabled() && !IsAlwaysOnEnabled() && !IsTraining())
857 return;
859 HotwordPrivateEventService* event_service =
860 BrowserContextKeyedAPIFactory<HotwordPrivateEventService>::Get(profile_);
861 // "enabled" isn't being changed, but piggy-back off the notification anyway.
862 if (event_service)
863 event_service->OnEnabledChanged(prefs::kHotwordSearchEnabled);
866 bool HotwordService::UserIsActive() {
867 #if defined(OS_CHROMEOS)
868 // Only support multiple profiles and profile switching in ChromeOS.
869 if (user_manager::UserManager::IsInitialized()) {
870 user_manager::User* user =
871 user_manager::UserManager::Get()->GetActiveUser();
872 if (user && user->is_profile_created())
873 return profile_ == ProfileManager::GetActiveUserProfile();
875 #endif
876 return true;