first_run.cc revision 58537e28ecd584eab876aee8be7156509866d23a
1// Copyright (c) 2012 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.
4
5#include "chrome/browser/first_run/first_run.h"
6
7#include <algorithm>
8
9#include "base/command_line.h"
10#include "base/compiler_specific.h"
11#include "base/file_util.h"
12#include "base/files/file_path.h"
13#include "base/lazy_instance.h"
14#include "base/memory/ref_counted.h"
15#include "base/message_loop/message_loop.h"
16#include "base/metrics/histogram.h"
17#include "base/path_service.h"
18#include "base/prefs/pref_service.h"
19#include "base/strings/stringprintf.h"
20#include "base/strings/utf_string_conversions.h"
21#include "build/build_config.h"
22#include "chrome/browser/browser_process.h"
23#include "chrome/browser/chrome_notification_types.h"
24#include "chrome/browser/extensions/extension_service.h"
25#include "chrome/browser/extensions/updater/extension_updater.h"
26#include "chrome/browser/first_run/first_run_internal.h"
27#include "chrome/browser/google/google_util.h"
28#include "chrome/browser/importer/external_process_importer_host.h"
29#include "chrome/browser/importer/importer_list.h"
30#include "chrome/browser/importer/importer_progress_observer.h"
31#include "chrome/browser/importer/importer_uma.h"
32#include "chrome/browser/importer/profile_writer.h"
33#include "chrome/browser/profiles/profiles_state.h"
34#include "chrome/browser/search_engines/template_url_service.h"
35#include "chrome/browser/search_engines/template_url_service_factory.h"
36#include "chrome/browser/shell_integration.h"
37#include "chrome/browser/signin/signin_manager.h"
38#include "chrome/browser/signin/signin_manager_factory.h"
39#include "chrome/browser/signin/signin_promo.h"
40#include "chrome/browser/signin/signin_tracker.h"
41#include "chrome/browser/ui/browser.h"
42#include "chrome/browser/ui/browser_finder.h"
43#include "chrome/browser/ui/global_error/global_error_service.h"
44#include "chrome/browser/ui/global_error/global_error_service_factory.h"
45#include "chrome/browser/ui/tabs/tab_strip_model.h"
46#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
47#include "chrome/common/chrome_paths.h"
48#include "chrome/common/chrome_switches.h"
49#include "chrome/common/pref_names.h"
50#include "chrome/common/url_constants.h"
51#include "chrome/installer/util/master_preferences.h"
52#include "chrome/installer/util/master_preferences_constants.h"
53#include "chrome/installer/util/util_constants.h"
54#include "components/user_prefs/pref_registry_syncable.h"
55#include "content/public/browser/notification_observer.h"
56#include "content/public/browser/notification_registrar.h"
57#include "content/public/browser/notification_service.h"
58#include "content/public/browser/notification_types.h"
59#include "content/public/browser/user_metrics.h"
60#include "content/public/browser/web_contents.h"
61#include "google_apis/gaia/gaia_auth_util.h"
62#include "url/gurl.h"
63
64using content::UserMetricsAction;
65
66namespace {
67
68// A bitfield formed from values in AutoImportState to record the state of
69// AutoImport. This is used in testing to verify import startup actions that
70// occur before an observer can be registered in the test.
71uint16 g_auto_import_state = first_run::AUTO_IMPORT_NONE;
72
73// Flags for functions of similar name.
74bool g_should_show_welcome_page = false;
75bool g_should_do_autofill_personal_data_manager_first_run = false;
76
77// This class acts as an observer for the ImporterProgressObserver::ImportEnded
78// callback. When the import process is started, certain errors may cause
79// ImportEnded() to be called synchronously, but the typical case is that
80// ImportEnded() is called asynchronously. Thus we have to handle both cases.
81class ImportEndedObserver : public importer::ImporterProgressObserver {
82 public:
83  ImportEndedObserver() : ended_(false),
84                          should_quit_message_loop_(false) {}
85  virtual ~ImportEndedObserver() {}
86
87  // importer::ImporterProgressObserver:
88  virtual void ImportStarted() OVERRIDE {}
89  virtual void ImportItemStarted(importer::ImportItem item) OVERRIDE {}
90  virtual void ImportItemEnded(importer::ImportItem item) OVERRIDE {}
91  virtual void ImportEnded() OVERRIDE {
92    ended_ = true;
93    if (should_quit_message_loop_)
94      base::MessageLoop::current()->Quit();
95  }
96
97  void set_should_quit_message_loop() {
98    should_quit_message_loop_ = true;
99  }
100
101  bool ended() const {
102    return ended_;
103  }
104
105 private:
106  // Set if the import has ended.
107  bool ended_;
108
109  bool should_quit_message_loop_;
110};
111
112// Helper class that performs delayed first-run tasks that need more of the
113// chrome infrastructure to be up and running before they can be attempted.
114class FirstRunDelayedTasks : public content::NotificationObserver {
115 public:
116  enum Tasks {
117    NO_TASK,
118    INSTALL_EXTENSIONS
119  };
120
121  explicit FirstRunDelayedTasks(Tasks task) {
122    if (task == INSTALL_EXTENSIONS) {
123      registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
124                     content::NotificationService::AllSources());
125    }
126    registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
127                   content::NotificationService::AllSources());
128  }
129
130  virtual void Observe(int type,
131                       const content::NotificationSource& source,
132                       const content::NotificationDetails& details) OVERRIDE {
133    // After processing the notification we always delete ourselves.
134    if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
135      DoExtensionWork(
136          content::Source<Profile>(source).ptr()->GetExtensionService());
137    }
138    delete this;
139  }
140
141 private:
142  // Private ctor forces it to be created only in the heap.
143  virtual ~FirstRunDelayedTasks() {}
144
145  // The extension work is to basically trigger an extension update check.
146  // If the extension specified in the master pref is older than the live
147  // extension it will get updated which is the same as get it installed.
148  void DoExtensionWork(ExtensionService* service) {
149    if (service)
150      service->updater()->CheckNow(extensions::ExtensionUpdater::CheckParams());
151  }
152
153  content::NotificationRegistrar registrar_;
154};
155
156// Installs a task to do an extensions update check once the extensions system
157// is running.
158void DoDelayedInstallExtensions() {
159  new FirstRunDelayedTasks(FirstRunDelayedTasks::INSTALL_EXTENSIONS);
160}
161
162void DoDelayedInstallExtensionsIfNeeded(
163    installer::MasterPreferences* install_prefs) {
164  DictionaryValue* extensions = 0;
165  if (install_prefs->GetExtensionsBlock(&extensions)) {
166    VLOG(1) << "Extensions block found in master preferences";
167    DoDelayedInstallExtensions();
168  }
169}
170
171base::FilePath GetDefaultPrefFilePath(bool create_profile_dir,
172                                      const base::FilePath& user_data_dir) {
173  base::FilePath default_pref_dir =
174      profiles::GetDefaultProfileDir(user_data_dir);
175  if (create_profile_dir) {
176    if (!base::PathExists(default_pref_dir)) {
177      if (!file_util::CreateDirectory(default_pref_dir))
178        return base::FilePath();
179    }
180  }
181  return profiles::GetProfilePrefsPath(default_pref_dir);
182}
183
184// Sets the |items| bitfield according to whether the import data specified by
185// |import_type| should be be auto imported or not.
186void SetImportItem(PrefService* user_prefs,
187                   const char* pref_path,
188                   int import_items,
189                   int dont_import_items,
190                   importer::ImportItem import_type,
191                   int* items) {
192  // Work out whether an item is to be imported according to what is specified
193  // in master preferences.
194  bool should_import = false;
195  bool master_pref_set =
196      ((import_items | dont_import_items) & import_type) != 0;
197  bool master_pref = ((import_items & ~dont_import_items) & import_type) != 0;
198
199  if (import_type == importer::HISTORY ||
200      (import_type != importer::FAVORITES &&
201       first_run::internal::IsOrganicFirstRun())) {
202    // History is always imported unless turned off in master_preferences.
203    // Search engines and home page are imported in organic builds only
204    // unless turned off in master_preferences.
205    should_import = !master_pref_set || master_pref;
206  } else {
207    // Bookmarks are never imported, unless turned on in master_preferences.
208    // Search engine and home page import behaviour is similar in non organic
209    // builds.
210    should_import = master_pref_set && master_pref;
211  }
212
213  // If an import policy is set, import items according to policy. If no master
214  // preference is set, but a corresponding recommended policy is set, import
215  // item according to recommended policy. If both a master preference and a
216  // recommended policy is set, the master preference wins. If neither
217  // recommended nor managed policies are set, import item according to what we
218  // worked out above.
219  if (master_pref_set)
220    user_prefs->SetBoolean(pref_path, should_import);
221
222  if (!user_prefs->FindPreference(pref_path)->IsDefaultValue()) {
223    if (user_prefs->GetBoolean(pref_path))
224      *items |= import_type;
225  } else { // no policy (recommended or managed) is set
226    if (should_import)
227      *items |= import_type;
228  }
229
230  user_prefs->ClearPref(pref_path);
231}
232
233// Launches the import, via |importer_host|, from |source_profile| into
234// |target_profile| for the items specified in the |items_to_import| bitfield.
235// This may be done in a separate process depending on the platform, but it will
236// always block until done.
237void ImportFromSourceProfile(ExternalProcessImporterHost* importer_host,
238                             const importer::SourceProfile& source_profile,
239                             Profile* target_profile,
240                             uint16 items_to_import) {
241  ImportEndedObserver observer;
242  importer_host->set_observer(&observer);
243  importer_host->StartImportSettings(source_profile,
244                                     target_profile,
245                                     items_to_import,
246                                     new ProfileWriter(target_profile));
247  // If the import process has not errored out, block on it.
248  if (!observer.ended()) {
249    observer.set_should_quit_message_loop();
250    base::MessageLoop::current()->Run();
251  }
252}
253
254// Imports bookmarks from an html file whose path is provided by
255// |import_bookmarks_path|.
256void ImportFromFile(Profile* profile,
257                    ExternalProcessImporterHost* file_importer_host,
258                    const std::string& import_bookmarks_path) {
259  importer::SourceProfile source_profile;
260  source_profile.importer_type = importer::TYPE_BOOKMARKS_FILE;
261
262  const base::FilePath::StringType& import_bookmarks_path_str =
263#if defined(OS_WIN)
264      UTF8ToUTF16(import_bookmarks_path);
265#else
266      import_bookmarks_path;
267#endif
268  source_profile.source_path = base::FilePath(import_bookmarks_path_str);
269
270  ImportFromSourceProfile(file_importer_host, source_profile, profile,
271                          importer::FAVORITES);
272  g_auto_import_state |= first_run::AUTO_IMPORT_BOOKMARKS_FILE_IMPORTED;
273}
274
275// Imports settings from the first profile in |importer_list|.
276void ImportSettings(Profile* profile,
277                    ExternalProcessImporterHost* importer_host,
278                    scoped_refptr<ImporterList> importer_list,
279                    int items_to_import) {
280  const importer::SourceProfile& source_profile =
281      importer_list->GetSourceProfileAt(0);
282
283  // Ensure that importers aren't requested to import items that they do not
284  // support. If there is no overlap, skip.
285  items_to_import &= source_profile.services_supported;
286  if (items_to_import == 0)
287    return;
288
289  ImportFromSourceProfile(importer_host, source_profile, profile,
290                          items_to_import);
291  g_auto_import_state |= first_run::AUTO_IMPORT_PROFILE_IMPORTED;
292}
293
294GURL UrlFromString(const std::string& in) {
295  return GURL(in);
296}
297
298void ConvertStringVectorToGURLVector(
299    const std::vector<std::string>& src,
300    std::vector<GURL>* ret) {
301  ret->resize(src.size());
302  std::transform(src.begin(), src.end(), ret->begin(), &UrlFromString);
303}
304
305// Show the first run search engine bubble at the first appropriate opportunity.
306// This bubble may be delayed by other UI, like global errors and sync promos.
307class FirstRunBubbleLauncher : public content::NotificationObserver {
308 public:
309  // Show the bubble at the first appropriate opportunity. This function
310  // instantiates a FirstRunBubbleLauncher, which manages its own lifetime.
311  static void ShowFirstRunBubbleSoon();
312
313 private:
314  FirstRunBubbleLauncher();
315  virtual ~FirstRunBubbleLauncher();
316
317  // content::NotificationObserver:
318  virtual void Observe(int type,
319                       const content::NotificationSource& source,
320                       const content::NotificationDetails& details) OVERRIDE;
321
322  content::NotificationRegistrar registrar_;
323
324  DISALLOW_COPY_AND_ASSIGN(FirstRunBubbleLauncher);
325};
326
327// static
328void FirstRunBubbleLauncher::ShowFirstRunBubbleSoon() {
329  SetShowFirstRunBubblePref(first_run::FIRST_RUN_BUBBLE_SHOW);
330  // This FirstRunBubbleLauncher instance will manage its own lifetime.
331  new FirstRunBubbleLauncher();
332}
333
334FirstRunBubbleLauncher::FirstRunBubbleLauncher() {
335  registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
336                 content::NotificationService::AllSources());
337
338  // This notification is required to observe the switch between the sync setup
339  // page and the general settings page.
340  registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
341                 content::NotificationService::AllSources());
342}
343
344FirstRunBubbleLauncher::~FirstRunBubbleLauncher() {}
345
346void FirstRunBubbleLauncher::Observe(
347    int type,
348    const content::NotificationSource& source,
349    const content::NotificationDetails& details) {
350  DCHECK(type == content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME ||
351         type == chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED);
352
353  Browser* browser = chrome::FindBrowserWithWebContents(
354      content::Source<content::WebContents>(source).ptr());
355  if (!browser || !browser->is_type_tabbed())
356    return;
357
358  // Check the preference to determine if the bubble should be shown.
359  PrefService* prefs = g_browser_process->local_state();
360  if (!prefs || prefs->GetInteger(prefs::kShowFirstRunBubbleOption) !=
361      first_run::FIRST_RUN_BUBBLE_SHOW) {
362    delete this;
363    return;
364  }
365
366  content::WebContents* contents =
367      browser->tab_strip_model()->GetActiveWebContents();
368
369  // Suppress the first run bubble if a Gaia sign in page, the continue
370  // URL for the sign in page or the sync setup page is showing.
371  if (contents &&
372      (gaia::IsGaiaSignonRealm(contents->GetURL().GetOrigin()) ||
373       signin::IsContinueUrlForWebBasedSigninFlow(contents->GetURL()) ||
374       contents->GetURL() == GURL(std::string(chrome::kChromeUISettingsURL) +
375                                  chrome::kSyncSetupSubPage))) {
376    return;
377  }
378
379  if (contents && contents->GetURL().SchemeIs(chrome::kChromeUIScheme)) {
380    // Suppress the first run bubble if 'make chrome metro' flow is showing.
381    if (contents->GetURL().host() == chrome::kChromeUIMetroFlowHost)
382      return;
383
384    // Suppress the first run bubble if the NTP sync promo bubble is showing
385    // or if sign in is in progress.
386    if (contents->GetURL().host() == chrome::kChromeUINewTabHost) {
387      Profile* profile =
388          Profile::FromBrowserContext(contents->GetBrowserContext());
389      SigninManagerBase* manager =
390          SigninManagerFactory::GetForProfile(profile);
391      bool signin_in_progress = manager && manager->AuthInProgress();
392      bool is_promo_bubble_visible =
393          profile->GetPrefs()->GetBoolean(prefs::kSignInPromoShowNTPBubble);
394
395      if (is_promo_bubble_visible || signin_in_progress)
396        return;
397    }
398  }
399
400  // Suppress the first run bubble if a global error bubble is pending.
401  GlobalErrorService* global_error_service =
402      GlobalErrorServiceFactory::GetForProfile(browser->profile());
403  if (global_error_service->GetFirstGlobalErrorWithBubbleView() != NULL)
404    return;
405
406  // Reset the preference and notifications to avoid showing the bubble again.
407  prefs->SetInteger(prefs::kShowFirstRunBubbleOption,
408                    first_run::FIRST_RUN_BUBBLE_DONT_SHOW);
409
410  // Show the bubble now and destroy this bubble launcher.
411  browser->ShowFirstRunBubble();
412  delete this;
413}
414
415}  // namespace
416
417namespace first_run {
418namespace internal {
419
420FirstRunState first_run_ = FIRST_RUN_UNKNOWN;
421
422static base::LazyInstance<base::FilePath> master_prefs_path_for_testing
423    = LAZY_INSTANCE_INITIALIZER;
424
425installer::MasterPreferences*
426    LoadMasterPrefs(base::FilePath* master_prefs_path) {
427  if (!master_prefs_path_for_testing.Get().empty())
428    *master_prefs_path = master_prefs_path_for_testing.Get();
429  else
430    *master_prefs_path = base::FilePath(MasterPrefsPath());
431  if (master_prefs_path->empty())
432    return NULL;
433  installer::MasterPreferences* install_prefs =
434      new installer::MasterPreferences(*master_prefs_path);
435  if (!install_prefs->read_from_file()) {
436    delete install_prefs;
437    return NULL;
438  }
439
440  return install_prefs;
441}
442
443bool CopyPrefFile(const base::FilePath& user_data_dir,
444                  const base::FilePath& master_prefs_path) {
445  base::FilePath user_prefs = GetDefaultPrefFilePath(true, user_data_dir);
446  if (user_prefs.empty())
447    return false;
448
449  // The master prefs are regular prefs so we can just copy the file
450  // to the default place and they just work.
451  return base::CopyFile(master_prefs_path, user_prefs);
452}
453
454void SetupMasterPrefsFromInstallPrefs(
455    const installer::MasterPreferences& install_prefs,
456    MasterPrefs* out_prefs) {
457  ConvertStringVectorToGURLVector(
458      install_prefs.GetFirstRunTabs(), &out_prefs->new_tabs);
459
460  install_prefs.GetInt(installer::master_preferences::kDistroPingDelay,
461                       &out_prefs->ping_delay);
462
463  bool value = false;
464  if (install_prefs.GetBool(
465          installer::master_preferences::kDistroImportSearchPref, &value)) {
466    if (value) {
467      out_prefs->do_import_items |= importer::SEARCH_ENGINES;
468    } else {
469      out_prefs->dont_import_items |= importer::SEARCH_ENGINES;
470    }
471  }
472
473  // If we're suppressing the first-run bubble, set that preference now.
474  // Otherwise, wait until the user has completed first run to set it, so the
475  // user is guaranteed to see the bubble iff he or she has completed the first
476  // run process.
477  if (install_prefs.GetBool(
478          installer::master_preferences::kDistroSuppressFirstRunBubble,
479          &value) && value)
480    SetShowFirstRunBubblePref(FIRST_RUN_BUBBLE_SUPPRESS);
481
482  if (install_prefs.GetBool(
483          installer::master_preferences::kDistroImportHistoryPref,
484          &value)) {
485    if (value) {
486      out_prefs->do_import_items |= importer::HISTORY;
487    } else {
488      out_prefs->dont_import_items |= importer::HISTORY;
489    }
490  }
491
492  std::string not_used;
493  out_prefs->homepage_defined = install_prefs.GetString(
494      prefs::kHomePage, &not_used);
495
496  if (install_prefs.GetBool(
497          installer::master_preferences::kDistroImportHomePagePref,
498          &value)) {
499    if (value) {
500      out_prefs->do_import_items |= importer::HOME_PAGE;
501    } else {
502      out_prefs->dont_import_items |= importer::HOME_PAGE;
503    }
504  }
505
506  // Bookmarks are never imported unless specifically turned on.
507  if (install_prefs.GetBool(
508          installer::master_preferences::kDistroImportBookmarksPref,
509          &value)) {
510    if (value)
511      out_prefs->do_import_items |= importer::FAVORITES;
512    else
513      out_prefs->dont_import_items |= importer::FAVORITES;
514  }
515
516  if (install_prefs.GetBool(
517          installer::master_preferences::kMakeChromeDefaultForUser,
518          &value) && value) {
519    out_prefs->make_chrome_default = true;
520  }
521
522  if (install_prefs.GetBool(
523          installer::master_preferences::kSuppressFirstRunDefaultBrowserPrompt,
524          &value) && value) {
525    out_prefs->suppress_first_run_default_browser_prompt = true;
526  }
527
528  install_prefs.GetString(
529      installer::master_preferences::kDistroImportBookmarksFromFilePref,
530      &out_prefs->import_bookmarks_path);
531
532  out_prefs->variations_seed = install_prefs.GetVariationsSeed();
533
534  install_prefs.GetString(
535      installer::master_preferences::kDistroSuppressDefaultBrowserPromptPref,
536      &out_prefs->suppress_default_browser_prompt_for_version);
537}
538
539void SetDefaultBrowser(installer::MasterPreferences* install_prefs){
540  // Even on the first run we only allow for the user choice to take effect if
541  // no policy has been set by the admin.
542  if (!g_browser_process->local_state()->IsManagedPreference(
543          prefs::kDefaultBrowserSettingEnabled)) {
544    bool value = false;
545    if (install_prefs->GetBool(
546            installer::master_preferences::kMakeChromeDefaultForUser,
547            &value) && value) {
548      ShellIntegration::SetAsDefaultBrowser();
549    }
550  } else {
551    if (g_browser_process->local_state()->GetBoolean(
552            prefs::kDefaultBrowserSettingEnabled)) {
553      ShellIntegration::SetAsDefaultBrowser();
554    }
555  }
556}
557
558bool CreateSentinel() {
559  base::FilePath first_run_sentinel;
560  if (!internal::GetFirstRunSentinelFilePath(&first_run_sentinel))
561    return false;
562  return file_util::WriteFile(first_run_sentinel, "", 0) != -1;
563}
564
565// -- Platform-specific functions --
566
567#if !defined(OS_LINUX) && !defined(OS_BSD)
568bool IsOrganicFirstRun() {
569  std::string brand;
570  google_util::GetBrand(&brand);
571  return google_util::IsOrganicFirstRun(brand);
572}
573#endif
574
575}  // namespace internal
576
577MasterPrefs::MasterPrefs()
578    : ping_delay(0),
579      homepage_defined(false),
580      do_import_items(0),
581      dont_import_items(0),
582      make_chrome_default(false),
583      suppress_first_run_default_browser_prompt(false) {
584}
585
586MasterPrefs::~MasterPrefs() {}
587
588bool IsChromeFirstRun() {
589  if (internal::first_run_ != internal::FIRST_RUN_UNKNOWN)
590    return internal::first_run_ == internal::FIRST_RUN_TRUE;
591
592  internal::first_run_ = internal::FIRST_RUN_FALSE;
593
594  base::FilePath first_run_sentinel;
595  const CommandLine* command_line = CommandLine::ForCurrentProcess();
596  if (command_line->HasSwitch(switches::kForceFirstRun)) {
597    internal::first_run_ = internal::FIRST_RUN_TRUE;
598  } else if (command_line->HasSwitch(switches::kCancelFirstRun)) {
599    internal::first_run_ = internal::FIRST_RUN_CANCEL;
600  } else if (!command_line->HasSwitch(switches::kNoFirstRun) &&
601             internal::GetFirstRunSentinelFilePath(&first_run_sentinel) &&
602             !base::PathExists(first_run_sentinel)) {
603    internal::first_run_ = internal::FIRST_RUN_TRUE;
604  }
605
606  return internal::first_run_ == internal::FIRST_RUN_TRUE;
607}
608
609bool IsFirstRunSuppressed(const CommandLine& command_line) {
610  return command_line.HasSwitch(switches::kCancelFirstRun) ||
611      command_line.HasSwitch(switches::kNoFirstRun);
612}
613
614void CreateSentinelIfNeeded() {
615  if (IsChromeFirstRun() ||
616      internal::first_run_ == internal::FIRST_RUN_CANCEL) {
617    internal::CreateSentinel();
618  }
619}
620
621std::string GetPingDelayPrefName() {
622  return base::StringPrintf("%s.%s",
623                            installer::master_preferences::kDistroDict,
624                            installer::master_preferences::kDistroPingDelay);
625}
626
627void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
628  registry->RegisterIntegerPref(
629      GetPingDelayPrefName().c_str(),
630      0,
631      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
632}
633
634bool RemoveSentinel() {
635  base::FilePath first_run_sentinel;
636  if (!internal::GetFirstRunSentinelFilePath(&first_run_sentinel))
637    return false;
638  return base::DeleteFile(first_run_sentinel, false);
639}
640
641bool SetShowFirstRunBubblePref(FirstRunBubbleOptions show_bubble_option) {
642  PrefService* local_state = g_browser_process->local_state();
643  if (!local_state)
644    return false;
645  if (local_state->GetInteger(
646          prefs::kShowFirstRunBubbleOption) != FIRST_RUN_BUBBLE_SUPPRESS) {
647    // Set the new state as long as the bubble wasn't explicitly suppressed
648    // already.
649    local_state->SetInteger(prefs::kShowFirstRunBubbleOption,
650                            show_bubble_option);
651  }
652  return true;
653}
654
655void SetShouldShowWelcomePage() {
656  g_should_show_welcome_page = true;
657}
658
659bool ShouldShowWelcomePage() {
660  bool retval = g_should_show_welcome_page;
661  g_should_show_welcome_page = false;
662  return retval;
663}
664
665void SetShouldDoPersonalDataManagerFirstRun() {
666  g_should_do_autofill_personal_data_manager_first_run = true;
667}
668
669bool ShouldDoPersonalDataManagerFirstRun() {
670  bool retval = g_should_do_autofill_personal_data_manager_first_run;
671  g_should_do_autofill_personal_data_manager_first_run = false;
672  return retval;
673}
674
675void LogFirstRunMetric(FirstRunBubbleMetric metric) {
676  UMA_HISTOGRAM_ENUMERATION("FirstRun.SearchEngineBubble", metric,
677                            NUM_FIRST_RUN_BUBBLE_METRICS);
678}
679
680void SetMasterPrefsPathForTesting(const base::FilePath& master_prefs) {
681  internal::master_prefs_path_for_testing.Get() = master_prefs;
682}
683
684ProcessMasterPreferencesResult ProcessMasterPreferences(
685    const base::FilePath& user_data_dir,
686    MasterPrefs* out_prefs) {
687  DCHECK(!user_data_dir.empty());
688
689  base::FilePath master_prefs_path;
690  scoped_ptr<installer::MasterPreferences>
691      install_prefs(internal::LoadMasterPrefs(&master_prefs_path));
692
693  // Default value in case master preferences is missing or corrupt, or
694  // ping_delay is missing.
695  out_prefs->ping_delay = 90;
696  if (install_prefs.get()) {
697    if (!internal::ShowPostInstallEULAIfNeeded(install_prefs.get()))
698      return EULA_EXIT_NOW;
699
700    if (!internal::CopyPrefFile(user_data_dir, master_prefs_path))
701      DLOG(ERROR) << "Failed to copy master_preferences to user data dir.";
702
703    DoDelayedInstallExtensionsIfNeeded(install_prefs.get());
704
705    internal::SetupMasterPrefsFromInstallPrefs(*install_prefs, out_prefs);
706
707    internal::SetDefaultBrowser(install_prefs.get());
708  }
709
710  return FIRST_RUN_PROCEED;
711}
712
713void AutoImport(
714    Profile* profile,
715    bool homepage_defined,
716    int import_items,
717    int dont_import_items,
718    const std::string& import_bookmarks_path) {
719  // Deletes itself.
720  ExternalProcessImporterHost* importer_host = new ExternalProcessImporterHost;
721
722  base::FilePath local_state_path;
723  PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
724  bool local_state_file_exists = base::PathExists(local_state_path);
725
726  scoped_refptr<ImporterList> importer_list(new ImporterList());
727  importer_list->DetectSourceProfilesHack(
728      g_browser_process->GetApplicationLocale());
729
730  // Do import if there is an available profile for us to import.
731  if (importer_list->count() > 0) {
732    // Don't show the warning dialog if import fails.
733    importer_host->set_headless();
734    int items = 0;
735
736    if (internal::IsOrganicFirstRun()) {
737      // Home page is imported in organic builds only unless turned off or
738      // defined in master_preferences.
739      if (homepage_defined) {
740        dont_import_items |= importer::HOME_PAGE;
741        if (import_items & importer::HOME_PAGE)
742          import_items &= ~importer::HOME_PAGE;
743      }
744      // Search engines are not imported automatically in organic builds if the
745      // user already has a user preferences directory.
746      if (local_state_file_exists) {
747        dont_import_items |= importer::SEARCH_ENGINES;
748        if (import_items & importer::SEARCH_ENGINES)
749          import_items &= ~importer::SEARCH_ENGINES;
750      }
751    }
752
753    PrefService* user_prefs = profile->GetPrefs();
754
755    SetImportItem(user_prefs,
756                  prefs::kImportHistory,
757                  import_items,
758                  dont_import_items,
759                  importer::HISTORY,
760                  &items);
761    SetImportItem(user_prefs,
762                  prefs::kImportHomepage,
763                  import_items,
764                  dont_import_items,
765                  importer::HOME_PAGE,
766                  &items);
767    SetImportItem(user_prefs,
768                  prefs::kImportSearchEngine,
769                  import_items,
770                  dont_import_items,
771                  importer::SEARCH_ENGINES,
772                  &items);
773    SetImportItem(user_prefs,
774                  prefs::kImportBookmarks,
775                  import_items,
776                  dont_import_items,
777                  importer::FAVORITES,
778                  &items);
779
780    importer::LogImporterUseToMetrics(
781        "AutoImport", importer_list->GetSourceProfileAt(0).importer_type);
782
783    ImportSettings(profile, importer_host, importer_list, items);
784  }
785
786  if (!import_bookmarks_path.empty()) {
787    // Deletes itself.
788    ExternalProcessImporterHost* file_importer_host =
789        new ExternalProcessImporterHost;
790    file_importer_host->set_headless();
791
792    ImportFromFile(profile, file_importer_host, import_bookmarks_path);
793  }
794
795  content::RecordAction(UserMetricsAction("FirstRunDef_Accept"));
796
797  g_auto_import_state |= AUTO_IMPORT_CALLED;
798}
799
800void DoPostImportTasks(Profile* profile, bool make_chrome_default) {
801  if (make_chrome_default &&
802      ShellIntegration::CanSetAsDefaultBrowser() ==
803          ShellIntegration::SET_DEFAULT_UNATTENDED) {
804    ShellIntegration::SetAsDefaultBrowser();
805  }
806
807  // Display the first run bubble if there is a default search provider.
808  TemplateURLService* template_url =
809      TemplateURLServiceFactory::GetForProfile(profile);
810  if (template_url && template_url->GetDefaultSearchProvider())
811    FirstRunBubbleLauncher::ShowFirstRunBubbleSoon();
812  SetShouldShowWelcomePage();
813  SetShouldDoPersonalDataManagerFirstRun();
814
815  internal::DoPostImportPlatformSpecificTasks(profile);
816}
817
818uint16 auto_import_state() {
819  return g_auto_import_state;
820}
821
822}  // namespace first_run
823