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