Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / first_run / first_run.cc
bloba5838be4461e51c4d8b4870b04e8f551cbcf8992
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/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/lazy_instance.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/metrics/histogram.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/run_loop.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_brand.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/prefs/chrome_pref_service_factory.h"
34 #include "chrome/browser/profiles/profile.h"
35 #include "chrome/browser/profiles/profiles_state.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_factory.h"
39 #include "chrome/browser/ui/browser.h"
40 #include "chrome/browser/ui/browser_finder.h"
41 #include "chrome/browser/ui/chrome_pages.h"
42 #include "chrome/browser/ui/global_error/global_error_service.h"
43 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
44 #include "chrome/browser/ui/tabs/tab_strip_model.h"
45 #include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
46 #include "chrome/common/chrome_constants.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/grit/locale_settings.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/pref_registry/pref_registry_syncable.h"
56 #include "components/search_engines/template_url_service.h"
57 #include "components/signin/core/browser/signin_manager.h"
58 #include "components/signin/core/browser/signin_tracker.h"
59 #include "content/public/browser/navigation_entry.h"
60 #include "content/public/browser/notification_observer.h"
61 #include "content/public/browser/notification_registrar.h"
62 #include "content/public/browser/notification_service.h"
63 #include "content/public/browser/notification_types.h"
64 #include "content/public/browser/user_metrics.h"
65 #include "content/public/browser/web_contents.h"
66 #include "extensions/browser/extension_system.h"
67 #include "google_apis/gaia/gaia_auth_util.h"
68 #include "ui/base/l10n/l10n_util.h"
69 #include "url/gurl.h"
71 using base::UserMetricsAction;
73 namespace {
75 // A bitfield formed from values in AutoImportState to record the state of
76 // AutoImport. This is used in testing to verify import startup actions that
77 // occur before an observer can be registered in the test.
78 uint16 g_auto_import_state = first_run::AUTO_IMPORT_NONE;
80 // Flags for functions of similar name.
81 bool g_should_show_welcome_page = false;
82 bool g_should_do_autofill_personal_data_manager_first_run = false;
84 // This class acts as an observer for the ImporterProgressObserver::ImportEnded
85 // callback. When the import process is started, certain errors may cause
86 // ImportEnded() to be called synchronously, but the typical case is that
87 // ImportEnded() is called asynchronously. Thus we have to handle both cases.
88 class ImportEndedObserver : public importer::ImporterProgressObserver {
89 public:
90 ImportEndedObserver() : ended_(false) {}
91 ~ImportEndedObserver() override {}
93 // importer::ImporterProgressObserver:
94 void ImportStarted() override {}
95 void ImportItemStarted(importer::ImportItem item) override {}
96 void ImportItemEnded(importer::ImportItem item) override {}
97 void ImportEnded() override {
98 ended_ = true;
99 if (!callback_for_import_end_.is_null())
100 callback_for_import_end_.Run();
103 void set_callback_for_import_end(const base::Closure& callback) {
104 callback_for_import_end_ = callback;
107 bool ended() const {
108 return ended_;
111 private:
112 // Set if the import has ended.
113 bool ended_;
115 base::Closure callback_for_import_end_;
117 DISALLOW_COPY_AND_ASSIGN(ImportEndedObserver);
120 // Helper class that performs delayed first-run tasks that need more of the
121 // chrome infrastructure to be up and running before they can be attempted.
122 class FirstRunDelayedTasks : public content::NotificationObserver {
123 public:
124 enum Tasks {
125 NO_TASK,
126 INSTALL_EXTENSIONS
129 explicit FirstRunDelayedTasks(Tasks task) {
130 if (task == INSTALL_EXTENSIONS) {
131 registrar_.Add(this,
132 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
133 content::NotificationService::AllSources());
135 registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
136 content::NotificationService::AllSources());
139 void Observe(int type,
140 const content::NotificationSource& source,
141 const content::NotificationDetails& details) override {
142 // After processing the notification we always delete ourselves.
143 if (type == extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED) {
144 Profile* profile = content::Source<Profile>(source).ptr();
145 ExtensionService* service =
146 extensions::ExtensionSystem::Get(profile)->extension_service();
147 DoExtensionWork(service);
149 delete this;
152 private:
153 // Private ctor forces it to be created only in the heap.
154 ~FirstRunDelayedTasks() override {}
156 // The extension work is to basically trigger an extension update check.
157 // If the extension specified in the master pref is older than the live
158 // extension it will get updated which is the same as get it installed.
159 void DoExtensionWork(ExtensionService* service) {
160 if (service)
161 service->updater()->CheckNow(extensions::ExtensionUpdater::CheckParams());
164 content::NotificationRegistrar registrar_;
167 // Installs a task to do an extensions update check once the extensions system
168 // is running.
169 void DoDelayedInstallExtensions() {
170 new FirstRunDelayedTasks(FirstRunDelayedTasks::INSTALL_EXTENSIONS);
173 void DoDelayedInstallExtensionsIfNeeded(
174 installer::MasterPreferences* install_prefs) {
175 base::DictionaryValue* extensions = 0;
176 if (install_prefs->GetExtensionsBlock(&extensions)) {
177 DVLOG(1) << "Extensions block found in master preferences";
178 DoDelayedInstallExtensions();
182 // Sets the |items| bitfield according to whether the import data specified by
183 // |import_type| should be be auto imported or not.
184 void SetImportItem(PrefService* user_prefs,
185 const char* pref_path,
186 int import_items,
187 int dont_import_items,
188 importer::ImportItem import_type,
189 int* items) {
190 // Work out whether an item is to be imported according to what is specified
191 // in master preferences.
192 bool should_import = false;
193 bool master_pref_set =
194 ((import_items | dont_import_items) & import_type) != 0;
195 bool master_pref = ((import_items & ~dont_import_items) & import_type) != 0;
197 if (import_type == importer::HISTORY ||
198 (import_type != importer::FAVORITES &&
199 first_run::internal::IsOrganicFirstRun())) {
200 // History is always imported unless turned off in master_preferences.
201 // Search engines and home page are imported in organic builds only
202 // unless turned off in master_preferences.
203 should_import = !master_pref_set || master_pref;
204 } else {
205 // Bookmarks are never imported, unless turned on in master_preferences.
206 // Search engine and home page import behaviour is similar in non organic
207 // builds.
208 should_import = master_pref_set && master_pref;
211 // If an import policy is set, import items according to policy. If no master
212 // preference is set, but a corresponding recommended policy is set, import
213 // item according to recommended policy. If both a master preference and a
214 // recommended policy is set, the master preference wins. If neither
215 // recommended nor managed policies are set, import item according to what we
216 // worked out above.
217 if (master_pref_set)
218 user_prefs->SetBoolean(pref_path, should_import);
220 if (!user_prefs->FindPreference(pref_path)->IsDefaultValue()) {
221 if (user_prefs->GetBoolean(pref_path))
222 *items |= import_type;
223 } else {
224 // no policy (recommended or managed) is set
225 if (should_import)
226 *items |= import_type;
229 user_prefs->ClearPref(pref_path);
232 // Launches the import, via |importer_host|, from |source_profile| into
233 // |target_profile| for the items specified in the |items_to_import| bitfield.
234 // This may be done in a separate process depending on the platform, but it will
235 // always block until done.
236 void ImportFromSourceProfile(ExternalProcessImporterHost* importer_host,
237 const importer::SourceProfile& source_profile,
238 Profile* target_profile,
239 uint16 items_to_import) {
240 ImportEndedObserver observer;
241 importer_host->set_observer(&observer);
242 importer_host->StartImportSettings(source_profile,
243 target_profile,
244 items_to_import,
245 new ProfileWriter(target_profile));
246 // If the import process has not errored out, block on it.
247 if (!observer.ended()) {
248 base::RunLoop loop;
249 observer.set_callback_for_import_end(loop.QuitClosure());
250 loop.Run();
251 observer.set_callback_for_import_end(base::Closure());
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_ptr<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 bool IsOnWelcomePage(content::WebContents* contents) {
307 // We have to check both the GetURL() similar to the other checks below, but
308 // also the original request url because the welcome page we use is a
309 // redirect.
310 GURL welcome_page(l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL));
311 return contents->GetURL() == welcome_page ||
312 (contents->GetController().GetVisibleEntry() &&
313 contents->GetController()
314 .GetVisibleEntry()
315 ->GetOriginalRequestURL() == welcome_page);
318 // Show the first run search engine bubble at the first appropriate opportunity.
319 // This bubble may be delayed by other UI, like global errors and sync promos.
320 class FirstRunBubbleLauncher : public content::NotificationObserver {
321 public:
322 // Show the bubble at the first appropriate opportunity. This function
323 // instantiates a FirstRunBubbleLauncher, which manages its own lifetime.
324 static void ShowFirstRunBubbleSoon();
326 private:
327 FirstRunBubbleLauncher();
328 ~FirstRunBubbleLauncher() override;
330 // content::NotificationObserver:
331 void Observe(int type,
332 const content::NotificationSource& source,
333 const content::NotificationDetails& details) override;
335 content::NotificationRegistrar registrar_;
337 DISALLOW_COPY_AND_ASSIGN(FirstRunBubbleLauncher);
340 // static
341 void FirstRunBubbleLauncher::ShowFirstRunBubbleSoon() {
342 SetShowFirstRunBubblePref(first_run::FIRST_RUN_BUBBLE_SHOW);
343 // This FirstRunBubbleLauncher instance will manage its own lifetime.
344 new FirstRunBubbleLauncher();
347 FirstRunBubbleLauncher::FirstRunBubbleLauncher() {
348 registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
349 content::NotificationService::AllSources());
351 // This notification is required to observe the switch between the sync setup
352 // page and the general settings page.
353 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED,
354 content::NotificationService::AllSources());
357 FirstRunBubbleLauncher::~FirstRunBubbleLauncher() {}
359 void FirstRunBubbleLauncher::Observe(
360 int type,
361 const content::NotificationSource& source,
362 const content::NotificationDetails& details) {
363 DCHECK(type == content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME ||
364 type == chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED);
366 Browser* browser = chrome::FindBrowserWithWebContents(
367 content::Source<content::WebContents>(source).ptr());
368 if (!browser || !browser->is_type_tabbed())
369 return;
371 // Check the preference to determine if the bubble should be shown.
372 PrefService* prefs = g_browser_process->local_state();
373 if (!prefs || prefs->GetInteger(prefs::kShowFirstRunBubbleOption) !=
374 first_run::FIRST_RUN_BUBBLE_SHOW) {
375 delete this;
376 return;
379 content::WebContents* contents =
380 browser->tab_strip_model()->GetActiveWebContents();
382 // Suppress the first run bubble if a Gaia sign in page or the sync setup
383 // page is showing.
384 if (contents && (contents->GetURL().GetOrigin().spec() ==
385 chrome::kChromeUIChromeSigninURL ||
386 gaia::IsGaiaSignonRealm(contents->GetURL().GetOrigin()) ||
387 contents->GetURL() ==
388 chrome::GetSettingsUrl(chrome::kSyncSetupSubPage) ||
389 IsOnWelcomePage(contents))) {
390 return;
393 if (contents && contents->GetURL().SchemeIs(content::kChromeUIScheme)) {
394 #if defined(OS_WIN)
395 // Suppress the first run bubble if 'make chrome metro' flow is showing.
396 if (contents->GetURL().host() == chrome::kChromeUIMetroFlowHost)
397 return;
398 #endif
400 // Suppress the first run bubble if the NTP sync promo bubble is showing
401 // or if sign in is in progress.
402 if (contents->GetURL().host() == chrome::kChromeUINewTabHost) {
403 Profile* profile =
404 Profile::FromBrowserContext(contents->GetBrowserContext());
405 SigninManagerBase* manager =
406 SigninManagerFactory::GetForProfile(profile);
407 bool signin_in_progress = manager && manager->AuthInProgress();
408 bool is_promo_bubble_visible =
409 profile->GetPrefs()->GetBoolean(prefs::kSignInPromoShowNTPBubble);
411 if (is_promo_bubble_visible || signin_in_progress)
412 return;
416 // Suppress the first run bubble if a global error bubble is pending.
417 GlobalErrorService* global_error_service =
418 GlobalErrorServiceFactory::GetForProfile(browser->profile());
419 if (global_error_service->GetFirstGlobalErrorWithBubbleView() != NULL)
420 return;
422 // Reset the preference and notifications to avoid showing the bubble again.
423 prefs->SetInteger(prefs::kShowFirstRunBubbleOption,
424 first_run::FIRST_RUN_BUBBLE_DONT_SHOW);
426 // Show the bubble now and destroy this bubble launcher.
427 browser->ShowFirstRunBubble();
428 delete this;
431 static base::LazyInstance<base::FilePath> master_prefs_path_for_testing
432 = LAZY_INSTANCE_INITIALIZER;
434 // Loads master preferences from the master preference file into the installer
435 // master preferences. Returns the pointer to installer::MasterPreferences
436 // object if successful; otherwise, returns NULL.
437 installer::MasterPreferences* LoadMasterPrefs() {
438 base::FilePath master_prefs_path;
439 if (!master_prefs_path_for_testing.Get().empty())
440 master_prefs_path = master_prefs_path_for_testing.Get();
441 else
442 master_prefs_path = base::FilePath(first_run::internal::MasterPrefsPath());
443 if (master_prefs_path.empty())
444 return NULL;
445 installer::MasterPreferences* install_prefs =
446 new installer::MasterPreferences(master_prefs_path);
447 if (!install_prefs->read_from_file()) {
448 delete install_prefs;
449 return NULL;
452 return install_prefs;
455 // Makes chrome the user's default browser according to policy or
456 // |make_chrome_default_for_user| if no policy is set.
457 void ProcessDefaultBrowserPolicy(bool make_chrome_default_for_user) {
458 // Only proceed if chrome can be made default unattended. The interactive case
459 // (Windows 8+) is handled by the first run default browser prompt.
460 if (ShellIntegration::CanSetAsDefaultBrowser() ==
461 ShellIntegration::SET_DEFAULT_UNATTENDED) {
462 // The policy has precedence over the user's choice.
463 if (g_browser_process->local_state()->IsManagedPreference(
464 prefs::kDefaultBrowserSettingEnabled)) {
465 if (g_browser_process->local_state()->GetBoolean(
466 prefs::kDefaultBrowserSettingEnabled)) {
467 ShellIntegration::SetAsDefaultBrowser();
469 } else if (make_chrome_default_for_user) {
470 ShellIntegration::SetAsDefaultBrowser();
475 } // namespace
477 namespace first_run {
478 namespace internal {
480 FirstRunState g_first_run = FIRST_RUN_UNKNOWN;
482 void SetupMasterPrefsFromInstallPrefs(
483 const installer::MasterPreferences& install_prefs,
484 MasterPrefs* out_prefs) {
485 ConvertStringVectorToGURLVector(
486 install_prefs.GetFirstRunTabs(), &out_prefs->new_tabs);
488 install_prefs.GetInt(installer::master_preferences::kDistroPingDelay,
489 &out_prefs->ping_delay);
491 bool value = false;
492 if (install_prefs.GetBool(
493 installer::master_preferences::kDistroImportSearchPref, &value)) {
494 if (value) {
495 out_prefs->do_import_items |= importer::SEARCH_ENGINES;
496 } else {
497 out_prefs->dont_import_items |= importer::SEARCH_ENGINES;
501 // If we're suppressing the first-run bubble, set that preference now.
502 // Otherwise, wait until the user has completed first run to set it, so the
503 // user is guaranteed to see the bubble iff he or she has completed the first
504 // run process.
505 if (install_prefs.GetBool(
506 installer::master_preferences::kDistroSuppressFirstRunBubble,
507 &value) && value)
508 SetShowFirstRunBubblePref(FIRST_RUN_BUBBLE_SUPPRESS);
510 if (install_prefs.GetBool(
511 installer::master_preferences::kDistroImportHistoryPref,
512 &value)) {
513 if (value) {
514 out_prefs->do_import_items |= importer::HISTORY;
515 } else {
516 out_prefs->dont_import_items |= importer::HISTORY;
520 std::string not_used;
521 out_prefs->homepage_defined = install_prefs.GetString(
522 prefs::kHomePage, &not_used);
524 if (install_prefs.GetBool(
525 installer::master_preferences::kDistroImportHomePagePref,
526 &value)) {
527 if (value) {
528 out_prefs->do_import_items |= importer::HOME_PAGE;
529 } else {
530 out_prefs->dont_import_items |= importer::HOME_PAGE;
534 // Bookmarks are never imported unless specifically turned on.
535 if (install_prefs.GetBool(
536 installer::master_preferences::kDistroImportBookmarksPref,
537 &value)) {
538 if (value)
539 out_prefs->do_import_items |= importer::FAVORITES;
540 else
541 out_prefs->dont_import_items |= importer::FAVORITES;
544 if (install_prefs.GetBool(
545 installer::master_preferences::kMakeChromeDefaultForUser,
546 &value) && value) {
547 out_prefs->make_chrome_default_for_user = true;
550 if (install_prefs.GetBool(
551 installer::master_preferences::kSuppressFirstRunDefaultBrowserPrompt,
552 &value) && value) {
553 out_prefs->suppress_first_run_default_browser_prompt = true;
556 install_prefs.GetString(
557 installer::master_preferences::kDistroImportBookmarksFromFilePref,
558 &out_prefs->import_bookmarks_path);
560 out_prefs->compressed_variations_seed =
561 install_prefs.GetCompressedVariationsSeed();
562 out_prefs->variations_seed = install_prefs.GetVariationsSeed();
563 out_prefs->variations_seed_signature =
564 install_prefs.GetVariationsSeedSignature();
566 install_prefs.GetString(
567 installer::master_preferences::kDistroSuppressDefaultBrowserPromptPref,
568 &out_prefs->suppress_default_browser_prompt_for_version);
570 if (install_prefs.GetBool(
571 installer::master_preferences::kDistroWelcomePageOnOSUpgradeEnabled,
572 &value) &&
573 !value) {
574 out_prefs->welcome_page_on_os_upgrade_enabled = false;
578 bool GetFirstRunSentinelFilePath(base::FilePath* path) {
579 base::FilePath user_data_dir;
580 if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
581 return false;
582 *path = user_data_dir.Append(chrome::kFirstRunSentinel);
583 return true;
586 bool CreateSentinel() {
587 base::FilePath first_run_sentinel;
588 return GetFirstRunSentinelFilePath(&first_run_sentinel) &&
589 base::WriteFile(first_run_sentinel, "", 0) != -1;
592 // -- Platform-specific functions --
594 #if !defined(OS_LINUX) && !defined(OS_BSD)
595 bool IsOrganicFirstRun() {
596 std::string brand;
597 google_brand::GetBrand(&brand);
598 return google_brand::IsOrganicFirstRun(brand);
600 #endif
602 } // namespace internal
604 MasterPrefs::MasterPrefs()
605 : ping_delay(0),
606 homepage_defined(false),
607 do_import_items(0),
608 dont_import_items(0),
609 make_chrome_default_for_user(false),
610 suppress_first_run_default_browser_prompt(false),
611 welcome_page_on_os_upgrade_enabled(true) {
614 MasterPrefs::~MasterPrefs() {}
616 bool IsChromeFirstRun() {
617 if (internal::g_first_run == internal::FIRST_RUN_UNKNOWN) {
618 internal::g_first_run = internal::FIRST_RUN_FALSE;
619 const base::CommandLine* command_line =
620 base::CommandLine::ForCurrentProcess();
621 if (command_line->HasSwitch(switches::kForceFirstRun) ||
622 (!command_line->HasSwitch(switches::kNoFirstRun) &&
623 !internal::IsFirstRunSentinelPresent())) {
624 internal::g_first_run = internal::FIRST_RUN_TRUE;
627 return internal::g_first_run == internal::FIRST_RUN_TRUE;
630 #if defined(OS_MACOSX)
631 bool IsFirstRunSuppressed(const base::CommandLine& command_line) {
632 return command_line.HasSwitch(switches::kNoFirstRun);
634 #endif
636 void CreateSentinelIfNeeded() {
637 if (IsChromeFirstRun())
638 internal::CreateSentinel();
641 std::string GetPingDelayPrefName() {
642 return base::StringPrintf("%s.%s",
643 installer::master_preferences::kDistroDict,
644 installer::master_preferences::kDistroPingDelay);
647 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
648 registry->RegisterIntegerPref(GetPingDelayPrefName().c_str(), 0);
651 bool SetShowFirstRunBubblePref(FirstRunBubbleOptions show_bubble_option) {
652 PrefService* local_state = g_browser_process->local_state();
653 if (!local_state)
654 return false;
655 if (local_state->GetInteger(
656 prefs::kShowFirstRunBubbleOption) != FIRST_RUN_BUBBLE_SUPPRESS) {
657 // Set the new state as long as the bubble wasn't explicitly suppressed
658 // already.
659 local_state->SetInteger(prefs::kShowFirstRunBubbleOption,
660 show_bubble_option);
662 return true;
665 void SetShouldShowWelcomePage() {
666 g_should_show_welcome_page = true;
669 bool ShouldShowWelcomePage() {
670 bool retval = g_should_show_welcome_page;
671 g_should_show_welcome_page = false;
672 return retval;
675 void SetShouldDoPersonalDataManagerFirstRun() {
676 g_should_do_autofill_personal_data_manager_first_run = true;
679 bool ShouldDoPersonalDataManagerFirstRun() {
680 bool retval = g_should_do_autofill_personal_data_manager_first_run;
681 g_should_do_autofill_personal_data_manager_first_run = false;
682 return retval;
685 void LogFirstRunMetric(FirstRunBubbleMetric metric) {
686 UMA_HISTOGRAM_ENUMERATION("FirstRun.SearchEngineBubble", metric,
687 NUM_FIRST_RUN_BUBBLE_METRICS);
690 void SetMasterPrefsPathForTesting(const base::FilePath& master_prefs) {
691 master_prefs_path_for_testing.Get() = master_prefs;
694 ProcessMasterPreferencesResult ProcessMasterPreferences(
695 const base::FilePath& user_data_dir,
696 MasterPrefs* out_prefs) {
697 DCHECK(!user_data_dir.empty());
699 scoped_ptr<installer::MasterPreferences> install_prefs(LoadMasterPrefs());
701 // Default value in case master preferences is missing or corrupt, or
702 // ping_delay is missing.
703 out_prefs->ping_delay = 90;
704 if (install_prefs.get()) {
705 if (!internal::ShowPostInstallEULAIfNeeded(install_prefs.get()))
706 return EULA_EXIT_NOW;
708 if (!chrome_prefs::InitializePrefsFromMasterPrefs(
709 profiles::GetDefaultProfileDir(user_data_dir),
710 install_prefs->master_dictionary())) {
711 DLOG(ERROR) << "Failed to initialize from master_preferences.";
714 DoDelayedInstallExtensionsIfNeeded(install_prefs.get());
716 internal::SetupMasterPrefsFromInstallPrefs(*install_prefs, out_prefs);
719 return FIRST_RUN_PROCEED;
722 void AutoImport(
723 Profile* profile,
724 bool homepage_defined,
725 int import_items,
726 int dont_import_items,
727 const std::string& import_bookmarks_path) {
728 base::FilePath local_state_path;
729 PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
730 bool local_state_file_exists = base::PathExists(local_state_path);
732 // It may be possible to do the if block below asynchronously. In which case,
733 // get rid of this RunLoop. http://crbug.com/366116.
734 base::RunLoop run_loop;
735 scoped_ptr<ImporterList> importer_list(new ImporterList());
736 importer_list->DetectSourceProfiles(
737 g_browser_process->GetApplicationLocale(),
738 false, // include_interactive_profiles?
739 run_loop.QuitClosure());
740 run_loop.Run();
742 // Do import if there is an available profile for us to import.
743 if (importer_list->count() > 0) {
744 if (internal::IsOrganicFirstRun()) {
745 // Home page is imported in organic builds only unless turned off or
746 // defined in master_preferences.
747 if (homepage_defined) {
748 dont_import_items |= importer::HOME_PAGE;
749 if (import_items & importer::HOME_PAGE)
750 import_items &= ~importer::HOME_PAGE;
752 // Search engines are not imported automatically in organic builds if the
753 // user already has a user preferences directory.
754 if (local_state_file_exists) {
755 dont_import_items |= importer::SEARCH_ENGINES;
756 if (import_items & importer::SEARCH_ENGINES)
757 import_items &= ~importer::SEARCH_ENGINES;
761 PrefService* user_prefs = profile->GetPrefs();
762 int items = 0;
764 SetImportItem(user_prefs,
765 prefs::kImportHistory,
766 import_items,
767 dont_import_items,
768 importer::HISTORY,
769 &items);
770 SetImportItem(user_prefs,
771 prefs::kImportHomepage,
772 import_items,
773 dont_import_items,
774 importer::HOME_PAGE,
775 &items);
776 SetImportItem(user_prefs,
777 prefs::kImportSearchEngine,
778 import_items,
779 dont_import_items,
780 importer::SEARCH_ENGINES,
781 &items);
782 SetImportItem(user_prefs,
783 prefs::kImportBookmarks,
784 import_items,
785 dont_import_items,
786 importer::FAVORITES,
787 &items);
789 // Deletes itself.
790 ExternalProcessImporterHost* importer_host =
791 new ExternalProcessImporterHost;
793 // Don't show the warning dialog if import fails.
794 importer_host->set_headless();
796 importer::LogImporterUseToMetrics(
797 "AutoImport", importer_list->GetSourceProfileAt(0).importer_type);
799 ImportSettings(profile, importer_host, importer_list.Pass(), items);
802 if (!import_bookmarks_path.empty()) {
803 // Deletes itself.
804 ExternalProcessImporterHost* file_importer_host =
805 new ExternalProcessImporterHost;
806 file_importer_host->set_headless();
808 ImportFromFile(profile, file_importer_host, import_bookmarks_path);
811 content::RecordAction(UserMetricsAction("FirstRunDef_Accept"));
813 g_auto_import_state |= AUTO_IMPORT_CALLED;
816 void DoPostImportTasks(Profile* profile, bool make_chrome_default_for_user) {
817 // Only set default browser after import as auto import relies on the current
818 // default browser to know what to import from.
819 ProcessDefaultBrowserPolicy(make_chrome_default_for_user);
821 // Display the first run bubble if there is a default search provider.
822 TemplateURLService* template_url =
823 TemplateURLServiceFactory::GetForProfile(profile);
824 if (template_url && template_url->GetDefaultSearchProvider())
825 FirstRunBubbleLauncher::ShowFirstRunBubbleSoon();
826 SetShouldShowWelcomePage();
827 SetShouldDoPersonalDataManagerFirstRun();
829 internal::DoPostImportPlatformSpecificTasks(profile);
832 uint16 auto_import_state() {
833 return g_auto_import_state;
836 } // namespace first_run