File: app_list_service_impl.cc

package info (click to toggle)
chromium-browser 41.0.2272.118-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 2,189,132 kB
  • sloc: cpp: 9,691,462; ansic: 3,341,451; python: 712,689; asm: 518,779; xml: 208,926; java: 169,820; sh: 119,353; perl: 68,907; makefile: 28,311; yacc: 13,305; objc: 11,385; tcl: 3,186; cs: 2,225; sql: 2,217; lex: 2,215; lisp: 1,349; pascal: 1,256; awk: 407; ruby: 155; sed: 53; php: 14; exp: 11
file content (416 lines) | stat: -rw-r--r-- 15,268 bytes parent folder | download
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
// 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/app_list_service_impl.h"

#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/time/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/app_list/app_list_view_delegate.h"
#include "chrome/browser/ui/app_list/profile_loader.h"
#include "chrome/browser/ui/app_list/profile_store.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "ui/app_list/app_list_model.h"

namespace {

const int kDiscoverabilityTimeoutMinutes = 60;

void SendAppListAppLaunch(int count) {
  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "Apps.AppListDailyAppLaunches", count, 1, 1000, 50);
  if (count > 0)
    UMA_HISTOGRAM_ENUMERATION("Apps.AppListHasLaunchedAppToday", 1, 2);
}

void SendAppListLaunch(int count) {
  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "Apps.AppListDailyLaunches", count, 1, 1000, 50);
  if (count > 0)
    UMA_HISTOGRAM_ENUMERATION("Apps.AppListHasLaunchedAppListToday", 1, 2);
}

bool SendDailyEventFrequency(
    const char* last_ping_pref,
    const char* count_pref,
    void (*send_callback)(int count)) {
  PrefService* local_state = g_browser_process->local_state();

  base::Time now = base::Time::Now();
  base::Time last = base::Time::FromInternalValue(local_state->GetInt64(
      last_ping_pref));
  int days = (now - last).InDays();
  if (days > 0) {
    send_callback(local_state->GetInteger(count_pref));
    local_state->SetInt64(
        last_ping_pref,
        (last + base::TimeDelta::FromDays(days)).ToInternalValue());
    local_state->SetInteger(count_pref, 0);
    return true;
  }
  return false;
}

void RecordDailyEventFrequency(
    const char* last_ping_pref,
    const char* count_pref,
    void (*send_callback)(int count)) {
  if (!g_browser_process)
    return;  // In a unit test.

  PrefService* local_state = g_browser_process->local_state();
  if (!local_state)
    return;  // In a unit test.

  int count = local_state->GetInteger(count_pref);
  local_state->SetInteger(count_pref, count + 1);
  if (SendDailyEventFrequency(last_ping_pref, count_pref, send_callback)) {
    local_state->SetInteger(count_pref, 1);
  }
}

class ProfileStoreImpl : public ProfileStore {
 public:
  explicit ProfileStoreImpl(ProfileManager* profile_manager)
      : profile_manager_(profile_manager),
        weak_factory_(this) {
  }

  void AddProfileObserver(ProfileInfoCacheObserver* observer) override {
    profile_manager_->GetProfileInfoCache().AddObserver(observer);
  }

  void LoadProfileAsync(const base::FilePath& path,
                        base::Callback<void(Profile*)> callback) override {
    profile_manager_->CreateProfileAsync(
        path,
        base::Bind(&ProfileStoreImpl::OnProfileCreated,
                   weak_factory_.GetWeakPtr(),
                   callback),
        base::string16(),
        base::string16(),
        std::string());
  }

  void OnProfileCreated(base::Callback<void(Profile*)> callback,
                        Profile* profile,
                        Profile::CreateStatus status) {
    switch (status) {
      case Profile::CREATE_STATUS_CREATED:
        break;
      case Profile::CREATE_STATUS_INITIALIZED:
        callback.Run(profile);
        break;
      case Profile::CREATE_STATUS_LOCAL_FAIL:
      case Profile::CREATE_STATUS_REMOTE_FAIL:
      case Profile::CREATE_STATUS_CANCELED:
        break;
      case Profile::MAX_CREATE_STATUS:
        NOTREACHED();
        break;
    }
  }

  Profile* GetProfileByPath(const base::FilePath& path) override {
    return profile_manager_->GetProfileByPath(path);
  }

  base::FilePath GetUserDataDir() override {
    return profile_manager_->user_data_dir();
  }

  bool IsProfileSupervised(const base::FilePath& profile_path) override {
    ProfileInfoCache& profile_info =
        g_browser_process->profile_manager()->GetProfileInfoCache();
    size_t profile_index = profile_info.GetIndexOfProfileWithPath(profile_path);
    return profile_index != std::string::npos &&
        profile_info.ProfileIsSupervisedAtIndex(profile_index);
  }

 private:
  ProfileManager* profile_manager_;
  base::WeakPtrFactory<ProfileStoreImpl> weak_factory_;
};

void RecordAppListDiscoverability(PrefService* local_state,
                                  bool is_startup_check) {
  // Since this task may be delayed, ensure it does not interfere with shutdown
  // when they unluckily coincide.
  if (browser_shutdown::IsTryingToQuit())
    return;

  int64 enable_time_value = local_state->GetInt64(prefs::kAppListEnableTime);
  if (enable_time_value == 0)
    return;  // Already recorded or never enabled.

  base::Time app_list_enable_time =
      base::Time::FromInternalValue(enable_time_value);
  if (is_startup_check) {
    // When checking at startup, only clear and record the "timeout" case,
    // otherwise wait for a timeout.
    base::TimeDelta time_remaining =
        app_list_enable_time +
        base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes) -
        base::Time::Now();
    if (time_remaining > base::TimeDelta()) {
      base::MessageLoop::current()->PostDelayedTask(
          FROM_HERE,
          base::Bind(&RecordAppListDiscoverability,
                     base::Unretained(local_state),
                     false),
          time_remaining);
      return;
    }
  }

  local_state->SetInt64(prefs::kAppListEnableTime, 0);

  AppListService::AppListEnableSource enable_source =
      static_cast<AppListService::AppListEnableSource>(
          local_state->GetInteger(prefs::kAppListEnableMethod));
  if (enable_source == AppListService::ENABLE_FOR_APP_INSTALL) {
    base::TimeDelta time_taken = base::Time::Now() - app_list_enable_time;
    // This means the user "discovered" the app launcher naturally, after it was
    // enabled on the first app install. Record how long it took to discover.
    // Note that the last bucket is essentially "not discovered": subtract 1
    // minute to account for clock inaccuracy.
    UMA_HISTOGRAM_CUSTOM_TIMES(
        "Apps.AppListTimeToDiscover",
        time_taken,
        base::TimeDelta::FromSeconds(1),
        base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes - 1),
        10 /* bucket_count */);
  }
  UMA_HISTOGRAM_ENUMERATION("Apps.AppListHowEnabled",
                            enable_source,
                            AppListService::ENABLE_NUM_ENABLE_SOURCES);
}

}  // namespace

void AppListServiceImpl::RecordAppListLaunch() {
  RecordDailyEventFrequency(prefs::kLastAppListLaunchPing,
                            prefs::kAppListLaunchCount,
                            &SendAppListLaunch);
  RecordAppListDiscoverability(local_state_, false);
}

// static
void AppListServiceImpl::RecordAppListAppLaunch() {
  RecordDailyEventFrequency(prefs::kLastAppListAppLaunchPing,
                            prefs::kAppListAppLaunchCount,
                            &SendAppListAppLaunch);
}

// static
void AppListServiceImpl::SendAppListStats() {
  if (!g_browser_process || g_browser_process->IsShuttingDown())
    return;

  SendDailyEventFrequency(prefs::kLastAppListLaunchPing,
                          prefs::kAppListLaunchCount,
                          &SendAppListLaunch);
  SendDailyEventFrequency(prefs::kLastAppListAppLaunchPing,
                          prefs::kAppListAppLaunchCount,
                          &SendAppListAppLaunch);
}

AppListServiceImpl::AppListServiceImpl()
    : profile_store_(
          new ProfileStoreImpl(g_browser_process->profile_manager())),
      command_line_(*base::CommandLine::ForCurrentProcess()),
      local_state_(g_browser_process->local_state()),
      profile_loader_(new ProfileLoader(profile_store_.get())),
      weak_factory_(this) {
  profile_store_->AddProfileObserver(this);
}

AppListServiceImpl::AppListServiceImpl(const base::CommandLine& command_line,
                                       PrefService* local_state,
                                       scoped_ptr<ProfileStore> profile_store)
    : profile_store_(profile_store.Pass()),
      command_line_(command_line),
      local_state_(local_state),
      profile_loader_(new ProfileLoader(profile_store_.get())),
      weak_factory_(this) {
  profile_store_->AddProfileObserver(this);
}

AppListServiceImpl::~AppListServiceImpl() {}

AppListViewDelegate* AppListServiceImpl::GetViewDelegate(Profile* profile) {
  if (!view_delegate_)
    view_delegate_.reset(new AppListViewDelegate(GetControllerDelegate()));
  view_delegate_->SetProfile(profile);
  return view_delegate_.get();
}

void AppListServiceImpl::SetAppListNextPaintCallback(void (*callback)()) {}

void AppListServiceImpl::Init(Profile* initial_profile) {}

base::FilePath AppListServiceImpl::GetProfilePath(
    const base::FilePath& user_data_dir) {
  std::string app_list_profile;
  if (local_state_->HasPrefPath(prefs::kAppListProfile))
    app_list_profile = local_state_->GetString(prefs::kAppListProfile);

  // If the user has no profile preference for the app launcher, default to the
  // last browser profile used.
  if (app_list_profile.empty() &&
      local_state_->HasPrefPath(prefs::kProfileLastUsed)) {
    app_list_profile = local_state_->GetString(prefs::kProfileLastUsed);
  }

  // If there is no last used profile recorded, use the initial profile.
  if (app_list_profile.empty())
    app_list_profile = chrome::kInitialProfile;

  return user_data_dir.AppendASCII(app_list_profile);
}

void AppListServiceImpl::SetProfilePath(const base::FilePath& profile_path) {
  local_state_->SetString(
      prefs::kAppListProfile,
      profile_path.BaseName().MaybeAsASCII());
}

void AppListServiceImpl::CreateShortcut() {}

void AppListServiceImpl::OnProfileWillBeRemoved(
    const base::FilePath& profile_path) {
  // We need to watch for profile removal to keep kAppListProfile updated, for
  // the case that the deleted profile is being used by the app list.
  std::string app_list_last_profile = local_state_->GetString(
      prefs::kAppListProfile);
  if (profile_path.BaseName().MaybeAsASCII() != app_list_last_profile)
    return;

  // Switch the app list over to a valid profile.
  // Before ProfileInfoCache::DeleteProfileFromCache() calls this function,
  // ProfileManager::ScheduleProfileForDeletion() will have checked to see if
  // the deleted profile was also "last used", and updated that setting with
  // something valid.
  local_state_->SetString(prefs::kAppListProfile,
                          local_state_->GetString(prefs::kProfileLastUsed));

  // If the app list was never shown, there won't be a |view_delegate_| yet.
  if (!view_delegate_)
    return;

  // The Chrome AppListViewDelegate now needs its profile cleared, because:
  //  1. it has many references to the profile and can't be profile-keyed, and
  //  2. the last used profile might not be loaded yet.
  //    - this loading is sometimes done by the ProfileManager asynchronously,
  //      so the app list can't just switch to that.
  // Only Mac supports showing the app list with a NULL profile, so tear down
  // the view.
  DestroyAppList();
  view_delegate_->SetProfile(NULL);
}

void AppListServiceImpl::Show() {
  profile_loader_->LoadProfileInvalidatingOtherLoads(
      GetProfilePath(profile_store_->GetUserDataDir()),
      base::Bind(&AppListServiceImpl::ShowForProfile,
                 weak_factory_.GetWeakPtr()));
}

void AppListServiceImpl::ShowForVoiceSearch(
    Profile* profile,
    const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
  ShowForProfile(profile);
  view_delegate_->ToggleSpeechRecognitionForHotword(preamble);
}

void AppListServiceImpl::ShowForAppInstall(Profile* profile,
                                           const std::string& extension_id,
                                           bool start_discovery_tracking) {
  if (start_discovery_tracking) {
    CreateForProfile(profile);
  } else {
    // Check if the app launcher has not yet been shown ever. Since this will
    // show it, if discoverability UMA hasn't yet been recorded, it needs to be
    // counted as undiscovered.
    if (local_state_->GetInt64(prefs::kAppListEnableTime) != 0) {
      local_state_->SetInteger(prefs::kAppListEnableMethod,
                               ENABLE_SHOWN_UNDISCOVERED);
    }
    ShowForProfile(profile);
  }
  if (extension_id.empty())
    return;  // Nothing to highlight. Only used in tests.

  // The only way an install can happen is with the profile already loaded. So,
  // ShowForProfile() can never be asynchronous, and the model is guaranteed to
  // exist after a show.
  DCHECK(view_delegate_->GetModel());
  view_delegate_->GetModel()
      ->top_level_item_list()
      ->HighlightItemInstalledFromUI(extension_id);
}

void AppListServiceImpl::EnableAppList(Profile* initial_profile,
                                       AppListEnableSource enable_source) {
  SetProfilePath(initial_profile->GetPath());
  // Always allow the webstore "enable" button to re-run the install flow.
  if (enable_source != AppListService::ENABLE_VIA_WEBSTORE_LINK &&
      local_state_->GetBoolean(prefs::kAppLauncherHasBeenEnabled)) {
    return;
  }

  local_state_->SetBoolean(prefs::kAppLauncherHasBeenEnabled, true);
  CreateShortcut();

  // UMA for launcher discoverability.
  local_state_->SetInt64(prefs::kAppListEnableTime,
                         base::Time::Now().ToInternalValue());
  local_state_->SetInteger(prefs::kAppListEnableMethod, enable_source);
  if (base::MessageLoop::current()) {
    // Ensure a value is recorded if the user "never" shows the app list. Note
    // there is no message loop in unit tests.
    base::MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&RecordAppListDiscoverability,
                   base::Unretained(local_state_),
                   false),
        base::TimeDelta::FromMinutes(kDiscoverabilityTimeoutMinutes));
  }
}

void AppListServiceImpl::InvalidatePendingProfileLoads() {
  profile_loader_->InvalidatePendingProfileLoads();
}

void AppListServiceImpl::PerformStartupChecks(Profile* initial_profile) {
  // Except in rare, once-off cases, this just checks that a pref is "0" and
  // returns.
  RecordAppListDiscoverability(local_state_, true);

  if (command_line_.HasSwitch(switches::kResetAppListInstallState))
    local_state_->SetBoolean(prefs::kAppLauncherHasBeenEnabled, false);

  if (command_line_.HasSwitch(switches::kEnableAppList))
    EnableAppList(initial_profile, ENABLE_VIA_COMMAND_LINE);

  if (!base::MessageLoop::current())
    return;  // In a unit test.

  // Send app list usage stats after a delay.
  const int kSendUsageStatsDelay = 5;
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&AppListServiceImpl::SendAppListStats),
      base::TimeDelta::FromSeconds(kSendUsageStatsDelay));
}