1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
|
// 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/ui/app_list/start_page_service.h"
#include <string>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/singleton.h"
#include "base/metrics/user_metrics.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/media/media_stream_infobar_delegate.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/recommended_apps.h"
#include "chrome/browser/ui/app_list/speech_auth_helper.h"
#include "chrome/browser/ui/app_list/speech_recognizer.h"
#include "chrome/browser/ui/app_list/start_page_observer.h"
#include "chrome/browser/ui/app_list/start_page_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/speech_recognition_session_preamble.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "extensions/browser/extension_system_provider.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/extension.h"
#include "net/base/network_change_notifier.h"
#include "ui/app_list/app_list_switches.h"
#if defined(OS_CHROMEOS)
#include "chromeos/audio/cras_audio_handler.h"
#endif
using base::RecordAction;
using base::UserMetricsAction;
namespace app_list {
namespace {
bool InSpeechRecognition(SpeechRecognitionState state) {
return state == SPEECH_RECOGNITION_RECOGNIZING ||
state == SPEECH_RECOGNITION_IN_SPEECH;
}
} // namespace
class StartPageService::ProfileDestroyObserver
: public content::NotificationObserver {
public:
explicit ProfileDestroyObserver(StartPageService* service)
: service_(service) {
registrar_.Add(this,
chrome::NOTIFICATION_PROFILE_DESTROYED,
content::Source<Profile>(service_->profile()));
}
~ProfileDestroyObserver() override {}
private:
// content::NotificationObserver
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) override {
DCHECK_EQ(chrome::NOTIFICATION_PROFILE_DESTROYED, type);
DCHECK_EQ(service_->profile(), content::Source<Profile>(source).ptr());
service_->Shutdown();
}
StartPageService* service_; // Owner of this class.
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(ProfileDestroyObserver);
};
class StartPageService::StartPageWebContentsDelegate
: public content::WebContentsDelegate {
public:
StartPageWebContentsDelegate() {}
~StartPageWebContentsDelegate() override {}
void RequestMediaAccessPermission(
content::WebContents* web_contents,
const content::MediaStreamRequest& request,
const content::MediaResponseCallback& callback) override {
if (MediaStreamInfoBarDelegate::Create(web_contents, request, callback))
NOTREACHED() << "Media stream not allowed for WebUI";
}
bool CheckMediaAccessPermission(content::WebContents* web_contents,
const GURL& security_origin,
content::MediaStreamType type) override {
return MediaCaptureDevicesDispatcher::GetInstance()
->CheckMediaAccessPermission(web_contents, security_origin, type);
}
private:
DISALLOW_COPY_AND_ASSIGN(StartPageWebContentsDelegate);
};
#if defined(OS_CHROMEOS)
class StartPageService::AudioStatus
: public chromeos::CrasAudioHandler::AudioObserver {
public:
explicit AudioStatus(StartPageService* start_page_service)
: start_page_service_(start_page_service) {
chromeos::CrasAudioHandler::Get()->AddAudioObserver(this);
CheckAndUpdate();
}
~AudioStatus() override {
chromeos::CrasAudioHandler::Get()->RemoveAudioObserver(this);
}
bool CanListen() {
chromeos::CrasAudioHandler* audio_handler =
chromeos::CrasAudioHandler::Get();
return (audio_handler->GetPrimaryActiveInputNode() != 0) &&
!audio_handler->IsInputMuted();
}
private:
void CheckAndUpdate() {
// TODO(mukai): If the system can listen, this should also restart the
// hotword recognition.
start_page_service_->OnMicrophoneChanged(CanListen());
}
// chromeos::CrasAudioHandler::AudioObserver:
void OnInputMuteChanged() override { CheckAndUpdate(); }
void OnActiveInputNodeChanged() override { CheckAndUpdate(); }
StartPageService* start_page_service_;
DISALLOW_COPY_AND_ASSIGN(AudioStatus);
};
#endif // OS_CHROMEOS
class StartPageService::NetworkChangeObserver
: public net::NetworkChangeNotifier::NetworkChangeObserver {
public:
explicit NetworkChangeObserver(StartPageService* start_page_service)
: start_page_service_(start_page_service) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// NOTE: This is used to detect network connectivity changes. However, what
// we really want is internet connectivity changes because voice recognition
// needs to talk to a web service. However, this information isn't
// available, so network changes are the best we can do.
net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
last_type_ = net::NetworkChangeNotifier::GetConnectionType();
// Handle the case where we're started with no network available.
if (last_type_ == net::NetworkChangeNotifier::CONNECTION_NONE)
start_page_service_->OnNetworkChanged(false);
}
~NetworkChangeObserver() override {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
}
private:
void OnNetworkChanged(
net::NetworkChangeNotifier::ConnectionType type) override {
// Threading note: NetworkChangeNotifier's contract is that observers are
// called on the same thread that they're registered. In this case, it
// should always be the UI thread.
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (type == net::NetworkChangeNotifier::CONNECTION_NONE) {
start_page_service_->OnNetworkChanged(false);
} else if (last_type_ == net::NetworkChangeNotifier::CONNECTION_NONE &&
type != net::NetworkChangeNotifier::CONNECTION_NONE) {
start_page_service_->OnNetworkChanged(true);
}
last_type_ = type;
}
StartPageService* start_page_service_;
net::NetworkChangeNotifier::ConnectionType last_type_;
DISALLOW_COPY_AND_ASSIGN(NetworkChangeObserver);
};
// static
StartPageService* StartPageService::Get(Profile* profile) {
return StartPageServiceFactory::GetForProfile(profile);
}
StartPageService::StartPageService(Profile* profile)
: profile_(profile),
profile_destroy_observer_(new ProfileDestroyObserver(this)),
recommended_apps_(new RecommendedApps(profile)),
state_(app_list::SPEECH_RECOGNITION_OFF),
speech_button_toggled_manually_(false),
speech_result_obtained_(false),
webui_finished_loading_(false),
speech_auth_helper_(new SpeechAuthHelper(profile, &clock_)),
network_available_(true),
microphone_available_(true),
weak_factory_(this) {
// If experimental hotwording is enabled, then we're always "ready".
// Transitioning into the "hotword recognizing" state is handled by the
// hotword extension.
if (HotwordService::IsExperimentalHotwordingEnabled()) {
state_ = app_list::SPEECH_RECOGNITION_READY;
}
if (app_list::switches::IsExperimentalAppListEnabled())
LoadContents();
network_change_observer_.reset(new NetworkChangeObserver(this));
}
StartPageService::~StartPageService() {}
void StartPageService::AddObserver(StartPageObserver* observer) {
observers_.AddObserver(observer);
}
void StartPageService::RemoveObserver(StartPageObserver* observer) {
observers_.RemoveObserver(observer);
}
void StartPageService::OnMicrophoneChanged(bool available) {
microphone_available_ = available;
UpdateRecognitionState();
}
void StartPageService::OnNetworkChanged(bool available) {
network_available_ = available;
UpdateRecognitionState();
}
void StartPageService::UpdateRecognitionState() {
if (microphone_available_ && network_available_) {
if (state_ == SPEECH_RECOGNITION_OFF)
OnSpeechRecognitionStateChanged(SPEECH_RECOGNITION_READY);
} else {
OnSpeechRecognitionStateChanged(SPEECH_RECOGNITION_OFF);
}
}
void StartPageService::AppListShown() {
if (!contents_) {
LoadContents();
} else if (contents_->GetWebUI() &&
!HotwordService::IsExperimentalHotwordingEnabled()) {
// If experimental hotwording is enabled, don't call onAppListShown.
// onAppListShown() initializes the web speech API, which is not used with
// experimental hotwording.
contents_->GetWebUI()->CallJavascriptFunction(
"appList.startPage.onAppListShown",
base::FundamentalValue(HotwordEnabled()));
}
#if defined(OS_CHROMEOS)
audio_status_.reset(new AudioStatus(this));
#endif
}
void StartPageService::AppListHidden() {
if (contents_->GetWebUI()) {
contents_->GetWebUI()->CallJavascriptFunction(
"appList.startPage.onAppListHidden");
}
if (!app_list::switches::IsExperimentalAppListEnabled())
UnloadContents();
if (HotwordService::IsExperimentalHotwordingEnabled() &&
speech_recognizer_) {
speech_recognizer_->Stop();
}
#if defined(OS_CHROMEOS)
audio_status_.reset();
#endif
}
void StartPageService::ToggleSpeechRecognition(
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
DCHECK(contents_);
speech_button_toggled_manually_ = true;
// Speech recognition under V2 hotwording does not depend in any way on the
// start page web contents. Do this code path first to make this explicit and
// easier to identify what code needs to be deleted when V2 hotwording is
// stable.
if (HotwordService::IsExperimentalHotwordingEnabled()) {
if (!speech_recognizer_) {
std::string profile_locale;
#if defined(OS_CHROMEOS)
profile_locale = profile_->GetPrefs()->GetString(
prefs::kApplicationLocale);
#endif
if (profile_locale.empty())
profile_locale = g_browser_process->GetApplicationLocale();
speech_recognizer_.reset(
new SpeechRecognizer(weak_factory_.GetWeakPtr(),
profile_->GetRequestContext(),
profile_locale));
}
speech_recognizer_->Start(preamble);
return;
}
if (!contents_->GetWebUI())
return;
if (!webui_finished_loading_) {
pending_webui_callbacks_.push_back(
base::Bind(&StartPageService::ToggleSpeechRecognition,
base::Unretained(this),
preamble));
return;
}
contents_->GetWebUI()->CallJavascriptFunction(
"appList.startPage.toggleSpeechRecognition");
}
bool StartPageService::HotwordEnabled() {
// Voice input for the launcher is unsupported on non-ChromeOS platforms.
// TODO(amistry): Make speech input, and hotwording, work on non-ChromeOS.
#if defined(OS_CHROMEOS)
if (HotwordService::IsExperimentalHotwordingEnabled()) {
HotwordService* service = HotwordServiceFactory::GetForProfile(profile_);
return state_ != SPEECH_RECOGNITION_OFF &&
HotwordServiceFactory::IsServiceAvailable(profile_) &&
service &&
(service->IsSometimesOnEnabled() || service->IsAlwaysOnEnabled());
}
return HotwordServiceFactory::IsServiceAvailable(profile_) &&
profile_->GetPrefs()->GetBoolean(prefs::kHotwordSearchEnabled);
#else
return false;
#endif
}
content::WebContents* StartPageService::GetStartPageContents() {
return app_list::switches::IsExperimentalAppListEnabled() ? contents_.get()
: NULL;
}
content::WebContents* StartPageService::GetSpeechRecognitionContents() {
if (app_list::switches::IsVoiceSearchEnabled()) {
if (!contents_)
LoadContents();
return contents_.get();
}
return NULL;
}
void StartPageService::OnSpeechResult(
const base::string16& query, bool is_final) {
if (is_final) {
speech_result_obtained_ = true;
RecordAction(UserMetricsAction("AppList_SearchedBySpeech"));
}
FOR_EACH_OBSERVER(StartPageObserver,
observers_,
OnSpeechResult(query, is_final));
}
void StartPageService::OnSpeechSoundLevelChanged(int16_t level) {
FOR_EACH_OBSERVER(StartPageObserver,
observers_,
OnSpeechSoundLevelChanged(level));
}
void StartPageService::OnSpeechRecognitionStateChanged(
SpeechRecognitionState new_state) {
#if defined(OS_CHROMEOS)
// Sometimes this can be called even though there are no audio input devices.
if (audio_status_ && !audio_status_->CanListen())
new_state = SPEECH_RECOGNITION_OFF;
#endif
if (!network_available_ || !microphone_available_)
new_state = SPEECH_RECOGNITION_OFF;
if (state_ == new_state)
return;
if (HotwordService::IsExperimentalHotwordingEnabled() &&
(new_state == SPEECH_RECOGNITION_READY ||
new_state == SPEECH_RECOGNITION_OFF) &&
speech_recognizer_) {
speech_recognizer_->Stop();
}
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"));
}
speech_button_toggled_manually_ = false;
speech_result_obtained_ = false;
state_ = new_state;
FOR_EACH_OBSERVER(StartPageObserver,
observers_,
OnSpeechRecognitionStateChanged(new_state));
}
void StartPageService::GetSpeechAuthParameters(std::string* auth_scope,
std::string* auth_token) {
if (HotwordService::IsExperimentalHotwordingEnabled()) {
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();
#if defined(OS_CHROMEOS)
audio_status_.reset();
#endif
speech_auth_helper_.reset();
network_change_observer_.reset();
}
void StartPageService::WebUILoaded() {
// There's a race condition between the WebUI loading, and calling its JS
// functions. Specifically, calling LoadContents() doesn't mean that the page
// has loaded, but several code paths make this assumption. This function
// allows us to defer calling JS functions until after the page has finished
// loading.
webui_finished_loading_ = true;
for (const auto& cb : pending_webui_callbacks_)
cb.Run();
pending_webui_callbacks_.clear();
}
void StartPageService::LoadContents() {
contents_.reset(content::WebContents::Create(
content::WebContents::CreateParams(profile_)));
contents_delegate_.reset(new StartPageWebContentsDelegate());
contents_->SetDelegate(contents_delegate_.get());
contents_->GetController().LoadURL(
GURL(chrome::kChromeUIAppListStartPageURL),
content::Referrer(),
ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
std::string());
}
void StartPageService::UnloadContents() {
contents_.reset();
webui_finished_loading_ = false;
}
} // namespace app_list
|