Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / ui / app_list / app_list_service_impl.cc
blob57397697e8fd66d3db61fcb57c1763253a74ae02
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/ui/app_list/app_list_service_impl.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/metrics/histogram.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/string16.h"
14 #include "base/time/time.h"
15 #include "chrome/browser/browser_process.h"
16 #include "chrome/browser/browser_shutdown.h"
17 #include "chrome/browser/profiles/profile_manager.h"
18 #include "chrome/browser/ui/app_list/app_list_view_delegate.h"
19 #include "chrome/browser/ui/app_list/profile_loader.h"
20 #include "chrome/browser/ui/app_list/profile_store.h"
21 #include "chrome/common/chrome_constants.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/pref_names.h"
24 #include "ui/app_list/app_list_model.h"
26 namespace {
28 const int kDiscoverabilityTimeoutMinutes = 60;
30 void SendAppListAppLaunch(int count) {
31 UMA_HISTOGRAM_CUSTOM_COUNTS(
32 "Apps.AppListDailyAppLaunches", count, 1, 1000, 50);
33 if (count > 0)
34 UMA_HISTOGRAM_ENUMERATION("Apps.AppListHasLaunchedAppToday", 1, 2);
37 void SendAppListLaunch(int count) {
38 UMA_HISTOGRAM_CUSTOM_COUNTS(
39 "Apps.AppListDailyLaunches", count, 1, 1000, 50);
40 if (count > 0)
41 UMA_HISTOGRAM_ENUMERATION("Apps.AppListHasLaunchedAppListToday", 1, 2);
44 bool SendDailyEventFrequency(
45 const char* last_ping_pref,
46 const char* count_pref,
47 void (*send_callback)(int count)) {
48 PrefService* local_state = g_browser_process->local_state();
50 base::Time now = base::Time::Now();
51 base::Time last = base::Time::FromInternalValue(local_state->GetInt64(
52 last_ping_pref));
53 int days = (now - last).InDays();
54 if (days > 0) {
55 send_callback(local_state->GetInteger(count_pref));
56 local_state->SetInt64(
57 last_ping_pref,
58 (last + base::TimeDelta::FromDays(days)).ToInternalValue());
59 local_state->SetInteger(count_pref, 0);
60 return true;
62 return false;
65 void RecordDailyEventFrequency(
66 const char* last_ping_pref,
67 const char* count_pref,
68 void (*send_callback)(int count)) {
69 if (!g_browser_process)
70 return; // In a unit test.
72 PrefService* local_state = g_browser_process->local_state();
73 if (!local_state)
74 return; // In a unit test.
76 int count = local_state->GetInteger(count_pref);
77 local_state->SetInteger(count_pref, count + 1);
78 if (SendDailyEventFrequency(last_ping_pref, count_pref, send_callback)) {
79 local_state->SetInteger(count_pref, 1);
83 class ProfileStoreImpl : public ProfileStore {
84 public:
85 explicit ProfileStoreImpl(ProfileManager* profile_manager)
86 : profile_manager_(profile_manager),
87 weak_factory_(this) {
90 void AddProfileObserver(ProfileInfoCacheObserver* observer) override {
91 profile_manager_->GetProfileInfoCache().AddObserver(observer);
94 void LoadProfileAsync(const base::FilePath& path,
95 base::Callback<void(Profile*)> callback) override {
96 profile_manager_->CreateProfileAsync(
97 path,
98 base::Bind(&ProfileStoreImpl::OnProfileCreated,
99 weak_factory_.GetWeakPtr(),
100 callback),
101 base::string16(),
102 base::string16(),
103 std::string());
106 void OnProfileCreated(base::Callback<void(Profile*)> callback,
107 Profile* profile,
108 Profile::CreateStatus status) {
109 switch (status) {
110 case Profile::CREATE_STATUS_CREATED:
111 break;
112 case Profile::CREATE_STATUS_INITIALIZED:
113 callback.Run(profile);
114 break;
115 case Profile::CREATE_STATUS_LOCAL_FAIL:
116 case Profile::CREATE_STATUS_REMOTE_FAIL:
117 case Profile::CREATE_STATUS_CANCELED:
118 break;
119 case Profile::MAX_CREATE_STATUS:
120 NOTREACHED();
121 break;
125 Profile* GetProfileByPath(const base::FilePath& path) override {
126 DCHECK(!IsProfileLocked(path));
127 return profile_manager_->GetProfileByPath(path);
130 base::FilePath GetUserDataDir() override {
131 return profile_manager_->user_data_dir();
134 bool IsProfileSupervised(const base::FilePath& profile_path) override {
135 ProfileInfoCache& profile_info =
136 g_browser_process->profile_manager()->GetProfileInfoCache();
137 size_t profile_index = profile_info.GetIndexOfProfileWithPath(profile_path);
138 return profile_index != std::string::npos &&
139 profile_info.ProfileIsSupervisedAtIndex(profile_index);
142 bool IsProfileLocked(const base::FilePath& profile_path) override {
143 ProfileInfoCache& profile_info =
144 g_browser_process->profile_manager()->GetProfileInfoCache();
145 size_t profile_index = profile_info.GetIndexOfProfileWithPath(profile_path);
146 return profile_index != std::string::npos &&
147 profile_info.ProfileIsSigninRequiredAtIndex(profile_index);
150 private:
151 ProfileManager* profile_manager_;
152 base::WeakPtrFactory<ProfileStoreImpl> weak_factory_;
155 void RecordAppListDiscoverability(PrefService* local_state,
156 bool is_startup_check) {
157 // Since this task may be delayed, ensure it does not interfere with shutdown
158 // when they unluckily coincide.
159 if (browser_shutdown::IsTryingToQuit())
160 return;
162 int64 enable_time_value = local_state->GetInt64(prefs::kAppListEnableTime);
163 if (enable_time_value == 0)
164 return; // Already recorded or never enabled.
166 base::Time app_list_enable_time =
167 base::Time::FromInternalValue(enable_time_value);
168 if (is_startup_check) {
169 // When checking at startup, only clear and record the "timeout" case,
170 // otherwise wait for a timeout.
171 base::TimeDelta time_remaining =
172 app_list_enable_time +
173 base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes) -
174 base::Time::Now();
175 if (time_remaining > base::TimeDelta()) {
176 base::MessageLoop::current()->PostDelayedTask(
177 FROM_HERE,
178 base::Bind(&RecordAppListDiscoverability,
179 base::Unretained(local_state),
180 false),
181 time_remaining);
182 return;
186 local_state->SetInt64(prefs::kAppListEnableTime, 0);
188 AppListService::AppListEnableSource enable_source =
189 static_cast<AppListService::AppListEnableSource>(
190 local_state->GetInteger(prefs::kAppListEnableMethod));
191 if (enable_source == AppListService::ENABLE_FOR_APP_INSTALL) {
192 base::TimeDelta time_taken = base::Time::Now() - app_list_enable_time;
193 // This means the user "discovered" the app launcher naturally, after it was
194 // enabled on the first app install. Record how long it took to discover.
195 // Note that the last bucket is essentially "not discovered": subtract 1
196 // minute to account for clock inaccuracy.
197 UMA_HISTOGRAM_CUSTOM_TIMES(
198 "Apps.AppListTimeToDiscover",
199 time_taken,
200 base::TimeDelta::FromSeconds(1),
201 base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes - 1),
202 10 /* bucket_count */);
204 UMA_HISTOGRAM_ENUMERATION("Apps.AppListHowEnabled",
205 enable_source,
206 AppListService::ENABLE_NUM_ENABLE_SOURCES);
209 } // namespace
211 void AppListServiceImpl::RecordAppListLaunch() {
212 RecordDailyEventFrequency(prefs::kLastAppListLaunchPing,
213 prefs::kAppListLaunchCount,
214 &SendAppListLaunch);
215 RecordAppListDiscoverability(local_state_, false);
216 RecordAppListLastLaunch();
219 // static
220 void AppListServiceImpl::RecordAppListAppLaunch() {
221 RecordDailyEventFrequency(prefs::kLastAppListAppLaunchPing,
222 prefs::kAppListAppLaunchCount,
223 &SendAppListAppLaunch);
226 // static
227 void AppListServiceImpl::RecordAppListLastLaunch() {
228 if (!g_browser_process)
229 return; // In a unit test.
231 PrefService* local_state = g_browser_process->local_state();
232 if (!local_state)
233 return; // In a unit test.
235 local_state->SetInt64(prefs::kAppListLastLaunchTime,
236 base::Time::Now().ToInternalValue());
239 // static
240 void AppListServiceImpl::SendAppListStats() {
241 if (!g_browser_process || g_browser_process->IsShuttingDown())
242 return;
244 SendDailyEventFrequency(prefs::kLastAppListLaunchPing,
245 prefs::kAppListLaunchCount,
246 &SendAppListLaunch);
247 SendDailyEventFrequency(prefs::kLastAppListAppLaunchPing,
248 prefs::kAppListAppLaunchCount,
249 &SendAppListAppLaunch);
252 AppListServiceImpl::AppListServiceImpl()
253 : profile_store_(
254 new ProfileStoreImpl(g_browser_process->profile_manager())),
255 command_line_(*base::CommandLine::ForCurrentProcess()),
256 local_state_(g_browser_process->local_state()),
257 profile_loader_(new ProfileLoader(profile_store_.get())),
258 weak_factory_(this) {
259 profile_store_->AddProfileObserver(this);
262 AppListServiceImpl::AppListServiceImpl(const base::CommandLine& command_line,
263 PrefService* local_state,
264 scoped_ptr<ProfileStore> profile_store)
265 : profile_store_(profile_store.Pass()),
266 command_line_(command_line),
267 local_state_(local_state),
268 profile_loader_(new ProfileLoader(profile_store_.get())),
269 weak_factory_(this) {
270 profile_store_->AddProfileObserver(this);
273 AppListServiceImpl::~AppListServiceImpl() {}
275 AppListViewDelegate* AppListServiceImpl::GetViewDelegate(Profile* profile) {
276 if (!view_delegate_)
277 view_delegate_.reset(new AppListViewDelegate(GetControllerDelegate()));
278 view_delegate_->SetProfile(profile);
279 return view_delegate_.get();
282 void AppListServiceImpl::SetAppListNextPaintCallback(void (*callback)()) {}
284 void AppListServiceImpl::Init(Profile* initial_profile) {}
286 base::FilePath AppListServiceImpl::GetProfilePath(
287 const base::FilePath& user_data_dir) {
288 std::string app_list_profile;
289 if (local_state_->HasPrefPath(prefs::kAppListProfile))
290 app_list_profile = local_state_->GetString(prefs::kAppListProfile);
292 // If the user has no profile preference for the app launcher, default to the
293 // last browser profile used.
294 if (app_list_profile.empty() &&
295 local_state_->HasPrefPath(prefs::kProfileLastUsed)) {
296 app_list_profile = local_state_->GetString(prefs::kProfileLastUsed);
299 // If there is no last used profile recorded, use the initial profile.
300 if (app_list_profile.empty())
301 app_list_profile = chrome::kInitialProfile;
303 return user_data_dir.AppendASCII(app_list_profile);
306 void AppListServiceImpl::SetProfilePath(const base::FilePath& profile_path) {
307 local_state_->SetString(
308 prefs::kAppListProfile,
309 profile_path.BaseName().MaybeAsASCII());
312 void AppListServiceImpl::CreateShortcut() {}
314 void AppListServiceImpl::OnProfileWillBeRemoved(
315 const base::FilePath& profile_path) {
316 // We need to watch for profile removal to keep kAppListProfile updated, for
317 // the case that the deleted profile is being used by the app list.
318 std::string app_list_last_profile = local_state_->GetString(
319 prefs::kAppListProfile);
320 if (profile_path.BaseName().MaybeAsASCII() != app_list_last_profile)
321 return;
323 // Switch the app list over to a valid profile.
324 // Before ProfileInfoCache::DeleteProfileFromCache() calls this function,
325 // ProfileManager::ScheduleProfileForDeletion() will have checked to see if
326 // the deleted profile was also "last used", and updated that setting with
327 // something valid.
328 local_state_->SetString(prefs::kAppListProfile,
329 local_state_->GetString(prefs::kProfileLastUsed));
331 // If the app list was never shown, there won't be a |view_delegate_| yet.
332 if (!view_delegate_)
333 return;
335 // The Chrome AppListViewDelegate now needs its profile cleared, because:
336 // 1. it has many references to the profile and can't be profile-keyed, and
337 // 2. the last used profile might not be loaded yet.
338 // - this loading is sometimes done by the ProfileManager asynchronously,
339 // so the app list can't just switch to that.
340 // Only Mac supports showing the app list with a NULL profile, so tear down
341 // the view.
342 DestroyAppList();
343 view_delegate_->SetProfile(NULL);
346 void AppListServiceImpl::Show() {
347 profile_loader_->LoadProfileInvalidatingOtherLoads(
348 GetProfilePath(profile_store_->GetUserDataDir()),
349 base::Bind(&AppListServiceImpl::ShowForProfile,
350 weak_factory_.GetWeakPtr()));
353 void AppListServiceImpl::ShowForVoiceSearch(
354 Profile* profile,
355 const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
356 ShowForProfile(profile);
357 view_delegate_->ToggleSpeechRecognitionForHotword(preamble);
360 void AppListServiceImpl::ShowForAppInstall(Profile* profile,
361 const std::string& extension_id,
362 bool start_discovery_tracking) {
363 if (start_discovery_tracking) {
364 CreateForProfile(profile);
365 } else {
366 // Check if the app launcher has not yet been shown ever. Since this will
367 // show it, if discoverability UMA hasn't yet been recorded, it needs to be
368 // counted as undiscovered.
369 if (local_state_->GetInt64(prefs::kAppListEnableTime) != 0) {
370 local_state_->SetInteger(prefs::kAppListEnableMethod,
371 ENABLE_SHOWN_UNDISCOVERED);
373 ShowForProfile(profile);
375 if (extension_id.empty())
376 return; // Nothing to highlight. Only used in tests.
378 // The only way an install can happen is with the profile already loaded. So,
379 // ShowForProfile() can never be asynchronous, and the model is guaranteed to
380 // exist after a show.
381 DCHECK(view_delegate_->GetModel());
382 view_delegate_->GetModel()
383 ->top_level_item_list()
384 ->HighlightItemInstalledFromUI(extension_id);
387 void AppListServiceImpl::EnableAppList(Profile* initial_profile,
388 AppListEnableSource enable_source) {
389 SetProfilePath(initial_profile->GetPath());
390 // Always allow the webstore "enable" button to re-run the install flow.
391 if (enable_source != AppListService::ENABLE_VIA_WEBSTORE_LINK &&
392 local_state_->GetBoolean(prefs::kAppLauncherHasBeenEnabled)) {
393 return;
396 local_state_->SetBoolean(prefs::kAppLauncherHasBeenEnabled, true);
397 CreateShortcut();
399 // UMA for launcher discoverability.
400 local_state_->SetInt64(prefs::kAppListEnableTime,
401 base::Time::Now().ToInternalValue());
402 local_state_->SetInteger(prefs::kAppListEnableMethod, enable_source);
403 if (base::MessageLoop::current()) {
404 // Ensure a value is recorded if the user "never" shows the app list. Note
405 // there is no message loop in unit tests.
406 base::MessageLoop::current()->PostDelayedTask(
407 FROM_HERE,
408 base::Bind(&RecordAppListDiscoverability,
409 base::Unretained(local_state_),
410 false),
411 base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes));
415 void AppListServiceImpl::InvalidatePendingProfileLoads() {
416 profile_loader_->InvalidatePendingProfileLoads();
419 void AppListServiceImpl::PerformStartupChecks(Profile* initial_profile) {
420 // Except in rare, once-off cases, this just checks that a pref is "0" and
421 // returns.
422 RecordAppListDiscoverability(local_state_, true);
424 if (command_line_.HasSwitch(switches::kResetAppListInstallState))
425 local_state_->SetBoolean(prefs::kAppLauncherHasBeenEnabled, false);
427 if (command_line_.HasSwitch(switches::kEnableAppList))
428 EnableAppList(initial_profile, ENABLE_VIA_COMMAND_LINE);
430 if (!base::MessageLoop::current())
431 return; // In a unit test.
433 // Send app list usage stats after a delay.
434 const int kSendUsageStatsDelay = 5;
435 base::MessageLoop::current()->PostDelayedTask(
436 FROM_HERE,
437 base::Bind(&AppListServiceImpl::SendAppListStats),
438 base::TimeDelta::FromSeconds(kSendUsageStatsDelay));