Home | History | Annotate | Download | only in startup
      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/ui/startup/startup_browser_creator_impl.h"
      6 
      7 #include <algorithm>
      8 #include <vector>
      9 
     10 #include "apps/app_restore_service.h"
     11 #include "apps/app_restore_service_factory.h"
     12 #include "base/bind.h"
     13 #include "base/bind_helpers.h"
     14 #include "base/command_line.h"
     15 #include "base/compiler_specific.h"
     16 #include "base/environment.h"
     17 #include "base/lazy_instance.h"
     18 #include "base/memory/scoped_ptr.h"
     19 #include "base/metrics/histogram.h"
     20 #include "base/metrics/statistics_recorder.h"
     21 #include "base/path_service.h"
     22 #include "base/prefs/pref_service.h"
     23 #include "base/strings/string_number_conversions.h"
     24 #include "base/strings/string_split.h"
     25 #include "base/strings/utf_string_conversions.h"
     26 #include "base/threading/thread_restrictions.h"
     27 #include "chrome/browser/apps/install_chrome_app.h"
     28 #include "chrome/browser/auto_launch_trial.h"
     29 #include "chrome/browser/browser_process.h"
     30 #include "chrome/browser/chrome_notification_types.h"
     31 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
     32 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
     33 #include "chrome/browser/defaults.h"
     34 #include "chrome/browser/extensions/extension_creator.h"
     35 #include "chrome/browser/extensions/extension_service.h"
     36 #include "chrome/browser/extensions/launch_util.h"
     37 #include "chrome/browser/extensions/pack_extension_job.h"
     38 #include "chrome/browser/first_run/first_run.h"
     39 #include "chrome/browser/infobars/infobar_service.h"
     40 #include "chrome/browser/net/predictor.h"
     41 #include "chrome/browser/notifications/desktop_notification_service.h"
     42 #include "chrome/browser/performance_monitor/startup_timer.h"
     43 #include "chrome/browser/prefs/incognito_mode_prefs.h"
     44 #include "chrome/browser/prefs/session_startup_pref.h"
     45 #include "chrome/browser/profiles/profile.h"
     46 #include "chrome/browser/profiles/profile_io_data.h"
     47 #include "chrome/browser/rlz/rlz.h"
     48 #include "chrome/browser/sessions/session_restore.h"
     49 #include "chrome/browser/sessions/session_service.h"
     50 #include "chrome/browser/sessions/session_service_factory.h"
     51 #include "chrome/browser/shell_integration.h"
     52 #include "chrome/browser/signin/signin_promo.h"
     53 #include "chrome/browser/ui/app_list/app_list_service.h"
     54 #include "chrome/browser/ui/browser_commands.h"
     55 #include "chrome/browser/ui/browser_finder.h"
     56 #include "chrome/browser/ui/browser_list.h"
     57 #include "chrome/browser/ui/browser_navigator.h"
     58 #include "chrome/browser/ui/browser_tabrestore.h"
     59 #include "chrome/browser/ui/browser_tabstrip.h"
     60 #include "chrome/browser/ui/browser_window.h"
     61 #include "chrome/browser/ui/extensions/application_launch.h"
     62 #include "chrome/browser/ui/host_desktop.h"
     63 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
     64 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
     65 #include "chrome/browser/ui/startup/default_browser_prompt.h"
     66 #include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
     67 #include "chrome/browser/ui/startup/obsolete_system_infobar_delegate.h"
     68 #include "chrome/browser/ui/startup/session_crashed_bubble.h"
     69 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
     70 #include "chrome/browser/ui/startup/startup_browser_creator.h"
     71 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
     72 #include "chrome/browser/ui/tabs/tab_strip_model.h"
     73 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
     74 #include "chrome/common/chrome_constants.h"
     75 #include "chrome/common/chrome_paths.h"
     76 #include "chrome/common/chrome_result_codes.h"
     77 #include "chrome/common/chrome_switches.h"
     78 #include "chrome/common/chrome_version_info.h"
     79 #include "chrome/common/extensions/extension_constants.h"
     80 #include "chrome/common/pref_names.h"
     81 #include "chrome/common/url_constants.h"
     82 #include "chrome/installer/util/browser_distribution.h"
     83 #include "components/google/core/browser/google_util.h"
     84 #include "content/public/browser/child_process_security_policy.h"
     85 #include "content/public/browser/dom_storage_context.h"
     86 #include "content/public/browser/notification_observer.h"
     87 #include "content/public/browser/notification_registrar.h"
     88 #include "content/public/browser/storage_partition.h"
     89 #include "content/public/browser/web_contents.h"
     90 #include "extensions/browser/extension_prefs.h"
     91 #include "extensions/browser/extension_registry.h"
     92 #include "extensions/browser/extension_system.h"
     93 #include "extensions/common/constants.h"
     94 #include "extensions/common/extension.h"
     95 #include "extensions/common/extension_set.h"
     96 #include "grit/locale_settings.h"
     97 #include "ui/base/l10n/l10n_util.h"
     98 #include "ui/base/resource/resource_bundle.h"
     99 
    100 #if defined(OS_MACOSX)
    101 #include "base/mac/mac_util.h"
    102 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
    103 #endif
    104 
    105 #if defined(OS_WIN)
    106 #include "base/win/windows_version.h"
    107 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
    108 #endif
    109 
    110 using content::ChildProcessSecurityPolicy;
    111 using content::WebContents;
    112 using extensions::Extension;
    113 
    114 namespace {
    115 
    116 // Utility functions ----------------------------------------------------------
    117 
    118 enum LaunchMode {
    119   LM_TO_BE_DECIDED = 0,       // Possibly direct launch or via a shortcut.
    120   LM_AS_WEBAPP,               // Launched as a installed web application.
    121   LM_WITH_URLS,               // Launched with urls in the cmd line.
    122   LM_SHORTCUT_NONE,           // Not launched from a shortcut.
    123   LM_SHORTCUT_NONAME,         // Launched from shortcut but no name available.
    124   LM_SHORTCUT_UNKNOWN,        // Launched from user-defined shortcut.
    125   LM_SHORTCUT_QUICKLAUNCH,    // Launched from the quick launch bar.
    126   LM_SHORTCUT_DESKTOP,        // Launched from a desktop shortcut.
    127   LM_SHORTCUT_TASKBAR,        // Launched from the taskbar.
    128   LM_LINUX_MAC_BEOS           // Other OS buckets start here.
    129 };
    130 
    131 #if defined(OS_WIN)
    132 // Undocumented flag in the startup info structure tells us what shortcut was
    133 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
    134 // more information. Confirmed to work on XP, Vista and Win7.
    135 LaunchMode GetLaunchShortcutKind() {
    136   STARTUPINFOW si = { sizeof(si) };
    137   GetStartupInfoW(&si);
    138   if (si.dwFlags & 0x800) {
    139     if (!si.lpTitle)
    140       return LM_SHORTCUT_NONAME;
    141     base::string16 shortcut(si.lpTitle);
    142     // The windows quick launch path is not localized.
    143     if (shortcut.find(L"\\Quick Launch\\") != base::string16::npos) {
    144       if (base::win::GetVersion() >= base::win::VERSION_WIN7)
    145         return LM_SHORTCUT_TASKBAR;
    146       else
    147         return LM_SHORTCUT_QUICKLAUNCH;
    148     }
    149     scoped_ptr<base::Environment> env(base::Environment::Create());
    150     std::string appdata_path;
    151     env->GetVar("USERPROFILE", &appdata_path);
    152     if (!appdata_path.empty() &&
    153         shortcut.find(base::ASCIIToWide(appdata_path)) != std::wstring::npos)
    154       return LM_SHORTCUT_DESKTOP;
    155     return LM_SHORTCUT_UNKNOWN;
    156   }
    157   return LM_SHORTCUT_NONE;
    158 }
    159 #else
    160 // TODO(cpu): Port to other platforms.
    161 LaunchMode GetLaunchShortcutKind() {
    162   return LM_LINUX_MAC_BEOS;
    163 }
    164 #endif
    165 
    166 // Log in a histogram the frequency of launching by the different methods. See
    167 // LaunchMode enum for the actual values of the buckets.
    168 void RecordLaunchModeHistogram(LaunchMode mode) {
    169   int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
    170   UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
    171 }
    172 
    173 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
    174   for (size_t i = 0; i < urls.size(); ++i) {
    175     StartupTab tab;
    176     tab.is_pinned = false;
    177     tab.url = urls[i];
    178     tabs->push_back(tab);
    179   }
    180 }
    181 
    182 // Return true if the command line option --app-id is used.  Set
    183 // |out_extension| to the app to open, and |out_launch_container|
    184 // to the type of window into which the app should be open.
    185 bool GetAppLaunchContainer(
    186     Profile* profile,
    187     const std::string& app_id,
    188     const Extension** out_extension,
    189     extensions::LaunchContainer* out_launch_container) {
    190 
    191   ExtensionService* extensions_service = profile->GetExtensionService();
    192   const Extension* extension =
    193       extensions_service->GetExtensionById(app_id, false);
    194   // The extension with id |app_id| may have been uninstalled.
    195   if (!extension)
    196     return false;
    197 
    198   // Don't launch platform apps in incognito mode.
    199   if (profile->IsOffTheRecord() && extension->is_platform_app())
    200     return false;
    201 
    202   // Look at preferences to find the right launch container. If no
    203   // preference is set, launch as a window.
    204   extensions::LaunchContainer launch_container = extensions::GetLaunchContainer(
    205       extensions::ExtensionPrefs::Get(profile), extension);
    206 
    207   if (!CommandLine::ForCurrentProcess()->HasSwitch(
    208            switches::kEnableStreamlinedHostedApps) &&
    209       !extensions::HasPreferredLaunchContainer(
    210            extensions::ExtensionPrefs::Get(profile), extension)) {
    211     launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
    212   }
    213 
    214   *out_extension = extension;
    215   *out_launch_container = launch_container;
    216   return true;
    217 }
    218 
    219 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
    220   CoreAppLauncherHandler::RecordAppLaunchType(
    221       extension_misc::APP_LAUNCH_CMD_LINE_APP,
    222       app_type);
    223 }
    224 
    225 void RecordAppLaunches(Profile* profile,
    226                        const std::vector<GURL>& cmd_line_urls,
    227                        StartupTabs& autolaunch_tabs) {
    228   const extensions::ExtensionSet& extensions =
    229       extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
    230   for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
    231     const extensions::Extension* extension =
    232         extensions.GetAppByURL(cmd_line_urls.at(i));
    233     if (extension) {
    234       CoreAppLauncherHandler::RecordAppLaunchType(
    235           extension_misc::APP_LAUNCH_CMD_LINE_URL,
    236           extension->GetType());
    237     }
    238   }
    239   for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
    240     const extensions::Extension* extension =
    241         extensions.GetAppByURL(autolaunch_tabs.at(i).url);
    242     if (extension) {
    243       CoreAppLauncherHandler::RecordAppLaunchType(
    244           extension_misc::APP_LAUNCH_AUTOLAUNCH,
    245           extension->GetType());
    246     }
    247   }
    248 }
    249 
    250 class WebContentsCloseObserver : public content::NotificationObserver {
    251  public:
    252   WebContentsCloseObserver() : contents_(NULL) {}
    253   virtual ~WebContentsCloseObserver() {}
    254 
    255   void SetContents(content::WebContents* contents) {
    256     DCHECK(!contents_);
    257     contents_ = contents;
    258 
    259     registrar_.Add(this,
    260                    content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
    261                    content::Source<content::WebContents>(contents_));
    262   }
    263 
    264   content::WebContents* contents() { return contents_; }
    265 
    266  private:
    267   // content::NotificationObserver overrides:
    268   virtual void Observe(int type,
    269                        const content::NotificationSource& source,
    270                        const content::NotificationDetails& details) OVERRIDE {
    271     DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
    272     contents_ = NULL;
    273   }
    274 
    275   content::WebContents* contents_;
    276   content::NotificationRegistrar registrar_;
    277 
    278   DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
    279 };
    280 
    281 // TODO(koz): Consolidate this function and remove the special casing.
    282 const Extension* GetPlatformApp(Profile* profile,
    283                                 const std::string& extension_id) {
    284   const Extension* extension =
    285       extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
    286           extension_id, extensions::ExtensionRegistry::EVERYTHING);
    287   return extension && extension->is_platform_app() ? extension : NULL;
    288 }
    289 
    290 }  // namespace
    291 
    292 namespace internals {
    293 
    294 GURL GetWelcomePageURL() {
    295   std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
    296   return GURL(welcome_url);
    297 }
    298 
    299 }  // namespace internals
    300 
    301 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
    302     const base::FilePath& cur_dir,
    303     const CommandLine& command_line,
    304     chrome::startup::IsFirstRun is_first_run)
    305     : cur_dir_(cur_dir),
    306       command_line_(command_line),
    307       profile_(NULL),
    308       browser_creator_(NULL),
    309       is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
    310 }
    311 
    312 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
    313     const base::FilePath& cur_dir,
    314     const CommandLine& command_line,
    315     StartupBrowserCreator* browser_creator,
    316     chrome::startup::IsFirstRun is_first_run)
    317     : cur_dir_(cur_dir),
    318       command_line_(command_line),
    319       profile_(NULL),
    320       browser_creator_(browser_creator),
    321       is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
    322 }
    323 
    324 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
    325 }
    326 
    327 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
    328                                        const std::vector<GURL>& urls_to_open,
    329                                        bool process_startup,
    330                                        chrome::HostDesktopType desktop_type) {
    331   DCHECK(profile);
    332   profile_ = profile;
    333 
    334   if (command_line_.HasSwitch(switches::kDnsLogDetails))
    335     chrome_browser_net::EnablePredictorDetailedLog(true);
    336   if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
    337       profile->GetNetworkPredictor()) {
    338     profile->GetNetworkPredictor()->EnablePredictor(false);
    339   }
    340 
    341   AppListService::InitAll(profile);
    342   if (command_line_.HasSwitch(switches::kAppId)) {
    343     std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
    344     const Extension* extension = GetPlatformApp(profile, app_id);
    345     // If |app_id| is a disabled or terminated platform app we handle it
    346     // specially here, otherwise it will be handled below.
    347     if (extension) {
    348       RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
    349       AppLaunchParams params(profile, extension,
    350                              extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW);
    351       params.command_line = command_line_;
    352       params.current_directory = cur_dir_;
    353       // If we are being launched from the command line, default to native
    354       // desktop.
    355       params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
    356       OpenApplicationWithReenablePrompt(params);
    357       return true;
    358     }
    359   } else if (command_line_.HasSwitch(switches::kShowAppList)) {
    360     // This switch is used for shortcuts on the native desktop.
    361     AppListService::RecordShowTimings(command_line_);
    362     AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
    363         ShowForProfile(profile);
    364     return true;
    365   }
    366 
    367   // Open the required browser windows and tabs. First, see if
    368   // we're being run as an application window. If so, the user
    369   // opened an app shortcut.  Don't restore tabs or open initial
    370   // URLs in that case. The user should see the window as an app,
    371   // not as chrome.
    372   // Special case is when app switches are passed but we do want to restore
    373   // session. In that case open app window + focus it after session is restored.
    374   content::WebContents* app_contents = NULL;
    375   if (OpenApplicationWindow(profile, &app_contents)) {
    376     RecordLaunchModeHistogram(LM_AS_WEBAPP);
    377   } else {
    378     RecordLaunchModeHistogram(urls_to_open.empty() ?
    379                               LM_TO_BE_DECIDED : LM_WITH_URLS);
    380 
    381     ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
    382 
    383     if (command_line_.HasSwitch(switches::kInstallChromeApp)) {
    384       install_chrome_app::InstallChromeApp(
    385           command_line_.GetSwitchValueASCII(switches::kInstallChromeApp));
    386     }
    387 
    388     // If this is an app launch, but we didn't open an app window, it may
    389     // be an app tab.
    390     OpenApplicationTab(profile);
    391 
    392 #if defined(OS_MACOSX)
    393     if (process_startup) {
    394       // Check whether the auto-update system needs to be promoted from user
    395       // to system.
    396       KeystoneInfoBar::PromotionInfoBar(profile);
    397     }
    398 #endif
    399   }
    400 
    401 #if defined(OS_WIN)
    402   if (process_startup)
    403     ShellIntegration::MigrateChromiumShortcuts();
    404 #endif  // defined(OS_WIN)
    405 
    406   return true;
    407 }
    408 
    409 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
    410                                             std::string* app_id) {
    411   if (command_line_.HasSwitch(switches::kApp)) {
    412     if (app_url)
    413       *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
    414     return true;
    415   }
    416   if (command_line_.HasSwitch(switches::kAppId)) {
    417     if (app_id)
    418       *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
    419     return true;
    420   }
    421   return false;
    422 }
    423 
    424 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
    425   std::string app_id;
    426   // App shortcuts to URLs always open in an app window.  Because this
    427   // function will open an app that should be in a tab, there is no need
    428   // to look at the app URL.  OpenApplicationWindow() will open app url
    429   // shortcuts.
    430   if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
    431     return false;
    432 
    433   extensions::LaunchContainer launch_container;
    434   const Extension* extension;
    435   if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
    436     return false;
    437 
    438   // If the user doesn't want to open a tab, fail.
    439   if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
    440     return false;
    441 
    442   RecordCmdLineAppHistogram(extension->GetType());
    443 
    444   WebContents* app_tab = OpenApplication(AppLaunchParams(
    445       profile, extension, extensions::LAUNCH_CONTAINER_TAB,
    446       NEW_FOREGROUND_TAB));
    447   return (app_tab != NULL);
    448 }
    449 
    450 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
    451     Profile* profile,
    452     content::WebContents** out_app_contents) {
    453   // Set |out_app_contents| to NULL early on (just in case).
    454   if (out_app_contents)
    455     *out_app_contents = NULL;
    456 
    457   std::string url_string, app_id;
    458   if (!IsAppLaunch(&url_string, &app_id))
    459     return false;
    460 
    461   // This can fail if the app_id is invalid.  It can also fail if the
    462   // extension is external, and has not yet been installed.
    463   // TODO(skerner): Do something reasonable here. Pop up a warning panel?
    464   // Open an URL to the gallery page of the extension id?
    465   if (!app_id.empty()) {
    466     extensions::LaunchContainer launch_container;
    467     const Extension* extension;
    468     if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
    469       return false;
    470 
    471     // TODO(skerner): Could pass in |extension| and |launch_container|,
    472     // and avoid calling GetAppLaunchContainer() both here and in
    473     // OpenApplicationTab().
    474 
    475     if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
    476       return false;
    477 
    478     RecordCmdLineAppHistogram(extension->GetType());
    479 
    480     AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW);
    481     params.command_line = command_line_;
    482     params.current_directory = cur_dir_;
    483     WebContents* tab_in_app_window = OpenApplication(params);
    484 
    485     if (out_app_contents)
    486       *out_app_contents = tab_in_app_window;
    487 
    488     // Platform apps fire off a launch event which may or may not open a window.
    489     return (tab_in_app_window != NULL || CanLaunchViaEvent(extension));
    490   }
    491 
    492   if (url_string.empty())
    493     return false;
    494 
    495 #if defined(OS_WIN)  // Fix up Windows shortcuts.
    496   ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
    497 #endif
    498   GURL url(url_string);
    499 
    500   // Restrict allowed URLs for --app switch.
    501   if (!url.is_empty() && url.is_valid()) {
    502     ChildProcessSecurityPolicy* policy =
    503         ChildProcessSecurityPolicy::GetInstance();
    504     if (policy->IsWebSafeScheme(url.scheme()) ||
    505         url.SchemeIs(url::kFileScheme)) {
    506       const extensions::Extension* extension =
    507           extensions::ExtensionRegistry::Get(profile)
    508               ->enabled_extensions().GetAppByURL(url);
    509       if (extension) {
    510         RecordCmdLineAppHistogram(extension->GetType());
    511       } else {
    512         CoreAppLauncherHandler::RecordAppLaunchType(
    513             extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
    514             extensions::Manifest::TYPE_HOSTED_APP);
    515       }
    516 
    517       WebContents* app_tab = OpenAppShortcutWindow(profile, url);
    518 
    519       if (out_app_contents)
    520         *out_app_contents = app_tab;
    521 
    522       return (app_tab != NULL);
    523     }
    524   }
    525   return false;
    526 }
    527 
    528 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
    529     bool process_startup,
    530     const std::vector<GURL>& urls_to_open,
    531     chrome::HostDesktopType desktop_type) {
    532   // If we're starting up in "background mode" (no open browser window) then
    533   // don't open any browser windows, unless kAutoLaunchAtStartup is also
    534   // specified.
    535   if (process_startup &&
    536       command_line_.HasSwitch(switches::kNoStartupWindow) &&
    537       !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
    538     return;
    539   }
    540 
    541 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
    542 #if defined(OS_WIN)
    543   if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
    544     // See if there are apps for this profile that should be launched on startup
    545     // due to a switch from Metro mode.
    546     app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
    547   }
    548 #endif
    549 
    550   if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
    551     // ProcessStartupURLs processed the urls, nothing else to do.
    552     return;
    553   }
    554 
    555   chrome::startup::IsProcessStartup is_process_startup = process_startup ?
    556       chrome::startup::IS_PROCESS_STARTUP :
    557       chrome::startup::IS_NOT_PROCESS_STARTUP;
    558   if (!process_startup) {
    559     // Even if we're not starting a new process, this may conceptually be
    560     // "startup" for the user and so should be handled in a similar way.  Eg.,
    561     // Chrome may have been running in the background due to an app with a
    562     // background page being installed, or running with only an app window
    563     // displayed.
    564     SessionService* service =
    565         SessionServiceFactory::GetForProfileForSessionRestore(profile_);
    566     if (service && service->ShouldNewWindowStartSession()) {
    567       // Restore the last session if any.
    568       if (!HasPendingUncleanExit(profile_) &&
    569           service->RestoreIfNecessary(urls_to_open)) {
    570         return;
    571       }
    572       // Open user-specified URLs like pinned tabs and startup tabs.
    573       Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
    574       if (browser) {
    575         AddInfoBarsIfNecessary(browser, is_process_startup);
    576         return;
    577       }
    578     }
    579   }
    580 
    581   // Session startup didn't occur, open the urls.
    582   Browser* browser = NULL;
    583   std::vector<GURL> adjust_urls = urls_to_open;
    584   if (adjust_urls.empty()) {
    585     AddStartupURLs(&adjust_urls);
    586   } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
    587     // Always open a list of urls in a window on the native desktop.
    588     browser = chrome::FindTabbedBrowser(profile_, false,
    589                                         chrome::HOST_DESKTOP_TYPE_NATIVE);
    590   }
    591   // This will launch a browser; prevent session restore.
    592   StartupBrowserCreator::in_synchronous_profile_launch_ = true;
    593   browser = OpenURLsInBrowser(browser, process_startup, adjust_urls,
    594                               desktop_type);
    595   StartupBrowserCreator::in_synchronous_profile_launch_ = false;
    596   AddInfoBarsIfNecessary(browser, is_process_startup);
    597 }
    598 
    599 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
    600     const std::vector<GURL>& urls_to_open,
    601     chrome::HostDesktopType desktop_type) {
    602   VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
    603   SessionStartupPref pref =
    604       StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
    605   if (pref.type == SessionStartupPref::LAST)
    606     VLOG(1) << "Pref: last";
    607   else if (pref.type == SessionStartupPref::URLS)
    608     VLOG(1) << "Pref: urls";
    609   else if (pref.type == SessionStartupPref::DEFAULT)
    610     VLOG(1) << "Pref: default";
    611 
    612   apps::AppRestoreService* restore_service =
    613       apps::AppRestoreServiceFactory::GetForProfile(profile_);
    614   // NULL in incognito mode.
    615   if (restore_service) {
    616     restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
    617         StartupBrowserCreator::WasRestarted()));
    618   }
    619 
    620   if (pref.type == SessionStartupPref::LAST) {
    621     if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
    622         !command_line_.HasSwitch(switches::kRestoreLastSession)) {
    623       // The last session crashed. It's possible automatically loading the
    624       // page will trigger another crash, locking the user out of chrome.
    625       // To avoid this, don't restore on startup but instead show the crashed
    626       // infobar.
    627       VLOG(1) << "Unclean exit; not processing";
    628       return false;
    629     }
    630 
    631     uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
    632     if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
    633         CommandLine::ForCurrentProcess()->HasSwitch(
    634             switches::kCreateBrowserOnStartupForTests)) {
    635       restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
    636     }
    637 
    638 #if defined(OS_MACOSX)
    639     // On Mac, when restoring a session with no windows, suppress the creation
    640     // of a new window in the case where the system is launching Chrome via a
    641     // login item or Lion's resume feature.
    642     if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
    643       restore_behavior = restore_behavior &
    644                          ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
    645     }
    646 #endif
    647 
    648     // Pause the StartupTimer. Since the restore here is synchronous, we can
    649     // keep these two metrics (browser startup time and session restore time)
    650     // separate.
    651     performance_monitor::StartupTimer::PauseTimer();
    652 
    653     // The startup code only executes for browsers launched in desktop mode.
    654     // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
    655     Browser* browser = SessionRestore::RestoreSession(
    656         profile_, NULL, desktop_type, restore_behavior,
    657         urls_to_open);
    658 
    659     performance_monitor::StartupTimer::UnpauseTimer();
    660 
    661     AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
    662     return true;
    663   }
    664 
    665   Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
    666   if (!browser)
    667     return false;
    668 
    669   AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
    670 
    671   // Session restore may occur if the startup preference is "last" or if the
    672   // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
    673   // to start deleting leftover data.
    674   if (pref.type != SessionStartupPref::LAST &&
    675       !HasPendingUncleanExit(profile_)) {
    676     content::BrowserContext::GetDefaultStoragePartition(profile_)->
    677         GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
    678   }
    679 
    680   return true;
    681 }
    682 
    683 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
    684     const std::vector<GURL>& urls_to_open,
    685     chrome::HostDesktopType desktop_type) {
    686   SessionStartupPref pref =
    687       StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
    688   StartupTabs tabs;
    689   // Pinned tabs should not be displayed when chrome is launched in incognito
    690   // mode. Also, no pages should be opened automatically if the session
    691   // crashed. Otherwise it might trigger another crash, locking the user out of
    692   // chrome. The crash infobar is shown in this case.
    693   if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
    694                                                  profile_->GetPrefs()) &&
    695       !HasPendingUncleanExit(profile_)) {
    696     tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
    697   }
    698 
    699   RecordAppLaunches(profile_, urls_to_open, tabs);
    700 
    701   if (!urls_to_open.empty()) {
    702     // If urls were specified on the command line, use them.
    703     UrlsToTabs(urls_to_open, &tabs);
    704   } else if (pref.type == SessionStartupPref::DEFAULT ||
    705              (is_first_run_ &&
    706               browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
    707     std::vector<GURL> urls;
    708     AddStartupURLs(&urls);
    709     UrlsToTabs(urls, &tabs);
    710   } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
    711              !HasPendingUncleanExit(profile_)) {
    712     // Only use the set of urls specified in preferences if nothing was
    713     // specified on the command line. Filter out any urls that are to be
    714     // restored by virtue of having been previously pinned.
    715     AddUniqueURLs(pref.urls, &tabs);
    716   } else if (pref.type == SessionStartupPref::HOMEPAGE) {
    717     // If 'homepage' selected, either by the user or by a policy, we should
    718     // have migrated them to another value.
    719     NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
    720   }
    721 
    722   if (tabs.empty())
    723     return NULL;
    724 
    725   Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
    726   return browser;
    727 }
    728 
    729 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
    730                                               StartupTabs* tabs) {
    731   size_t num_existing_tabs = tabs->size();
    732   for (size_t i = 0; i < urls.size(); ++i) {
    733     bool in_tabs = false;
    734     for (size_t j = 0; j < num_existing_tabs; ++j) {
    735       if (urls[i] == (*tabs)[j].url) {
    736         in_tabs = true;
    737         break;
    738       }
    739     }
    740     if (!in_tabs) {
    741       StartupTab tab;
    742       tab.is_pinned = false;
    743       tab.url = urls[i];
    744       tabs->push_back(tab);
    745     }
    746   }
    747 }
    748 
    749 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
    750     Browser* browser,
    751     bool process_startup,
    752     const std::vector<GURL>& urls,
    753     chrome::HostDesktopType desktop_type) {
    754   StartupTabs tabs;
    755   UrlsToTabs(urls, &tabs);
    756   return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
    757 }
    758 
    759 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
    760     Browser* browser,
    761     bool process_startup,
    762     const StartupTabs& tabs,
    763     chrome::HostDesktopType desktop_type) {
    764   DCHECK(!tabs.empty());
    765 
    766   // If we don't yet have a profile, try to use the one we're given from
    767   // |browser|. While we may not end up actually using |browser| (since it
    768   // could be a popup window), we can at least use the profile.
    769   if (!profile_ && browser)
    770     profile_ = browser->profile();
    771 
    772   if (!browser || !browser->is_type_tabbed())
    773     browser = new Browser(Browser::CreateParams(profile_, desktop_type));
    774 
    775   bool first_tab = true;
    776   ProtocolHandlerRegistry* registry = profile_ ?
    777       ProtocolHandlerRegistryFactory::GetForProfile(profile_) : NULL;
    778   for (size_t i = 0; i < tabs.size(); ++i) {
    779     // We skip URLs that we'd have to launch an external protocol handler for.
    780     // This avoids us getting into an infinite loop asking ourselves to open
    781     // a URL, should the handler be (incorrectly) configured to be us. Anyone
    782     // asking us to open such a URL should really ask the handler directly.
    783     bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
    784         (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
    785     if (!process_startup && !handled_by_chrome)
    786       continue;
    787 
    788     int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
    789                                 TabStripModel::ADD_NONE;
    790     add_types |= TabStripModel::ADD_FORCE_INDEX;
    791     if (tabs[i].is_pinned)
    792       add_types |= TabStripModel::ADD_PINNED;
    793 
    794     chrome::NavigateParams params(browser, tabs[i].url,
    795                                   content::PAGE_TRANSITION_AUTO_TOPLEVEL);
    796     params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
    797     params.tabstrip_add_types = add_types;
    798     params.extension_app_id = tabs[i].app_id;
    799 
    800 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
    801     if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
    802       params.extra_headers = RLZTracker::GetAccessPointHttpHeader(
    803           RLZTracker::ChromeHomePage());
    804     }
    805 #endif  // defined(ENABLE_RLZ) && !defined(OS_IOS)
    806 
    807     chrome::Navigate(&params);
    808 
    809     first_tab = false;
    810   }
    811   if (!browser->tab_strip_model()->GetActiveWebContents()) {
    812     // TODO: this is a work around for 110909. Figure out why it's needed.
    813     if (!browser->tab_strip_model()->count())
    814       chrome::AddTabAt(browser, GURL(), -1, true);
    815     else
    816       browser->tab_strip_model()->ActivateTabAt(0, false);
    817   }
    818 
    819   // The default behavior is to show the window, as expressed by the default
    820   // value of StartupBrowserCreated::show_main_browser_window_. If this was set
    821   // to true ahead of this place, it means another task must have been spawned
    822   // to take care of that.
    823   if (!browser_creator_ || browser_creator_->show_main_browser_window())
    824     browser->window()->Show();
    825 
    826   // In kiosk mode, we want to always be fullscreen, so switch to that now.
    827   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
    828       CommandLine::ForCurrentProcess()->HasSwitch(switches::kStartFullscreen))
    829     chrome::ToggleFullscreenMode(browser);
    830 
    831   return browser;
    832 }
    833 
    834 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
    835     Browser* browser,
    836     chrome::startup::IsProcessStartup is_process_startup) {
    837   if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
    838     return;
    839 
    840   if (HasPendingUncleanExit(browser->profile()) &&
    841       !ShowSessionCrashedBubble(browser)) {
    842     SessionCrashedInfoBarDelegate::Create(browser);
    843   }
    844 
    845   // The below info bars are only added to the first profile which is launched.
    846   // Other profiles might be restoring the browsing sessions asynchronously,
    847   // so we cannot add the info bars to the focused tabs here.
    848   if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP &&
    849       !command_line_.HasSwitch(switches::kTestType)) {
    850     chrome::ShowBadFlagsPrompt(browser);
    851     GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
    852         browser->tab_strip_model()->GetActiveWebContents()));
    853     ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
    854         browser->tab_strip_model()->GetActiveWebContents()));
    855 
    856 #if !defined(OS_CHROMEOS)
    857     if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
    858       // Generally, the default browser prompt should not be shown on first
    859       // run. However, when the set-as-default dialog has been suppressed, we
    860       // need to allow it.
    861       if ((!is_first_run_ ||
    862            (browser_creator_ &&
    863             browser_creator_->is_default_browser_dialog_suppressed())) &&
    864           !chrome::ShowAutolaunchPrompt(browser)) {
    865         chrome::ShowDefaultBrowserPrompt(profile_,
    866                                          browser->host_desktop_type());
    867       }
    868     }
    869 #endif
    870   }
    871 }
    872 
    873 void StartupBrowserCreatorImpl::AddStartupURLs(
    874     std::vector<GURL>* startup_urls) const {
    875   // TODO(atwilson): Simplify the logic that decides which tabs to open on
    876   // start-up and make it more consistent. http://crbug.com/248883
    877 
    878   // If we have urls specified by the first run master preferences use them
    879   // and nothing else.
    880   if (browser_creator_ && startup_urls->empty()) {
    881     if (!browser_creator_->first_run_tabs_.empty()) {
    882       std::vector<GURL>::iterator it =
    883           browser_creator_->first_run_tabs_.begin();
    884       while (it != browser_creator_->first_run_tabs_.end()) {
    885         // Replace magic names for the actual urls.
    886         if (it->host() == "new_tab_page") {
    887           startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
    888         } else if (it->host() == "welcome_page") {
    889           startup_urls->push_back(internals::GetWelcomePageURL());
    890         } else {
    891           startup_urls->push_back(*it);
    892         }
    893         ++it;
    894       }
    895       browser_creator_->first_run_tabs_.clear();
    896     }
    897   }
    898 
    899   // Otherwise open at least the new tab page (and the welcome page, if this
    900   // is the first time the browser is being started), or the set of URLs
    901   // specified on the command line.
    902   if (startup_urls->empty()) {
    903     startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
    904     if (first_run::ShouldShowWelcomePage())
    905       startup_urls->push_back(internals::GetWelcomePageURL());
    906   }
    907 
    908   if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
    909     signin::DidShowPromoAtStartup(profile_);
    910 
    911     const GURL sync_promo_url = signin::GetPromoURL(signin::SOURCE_START_PAGE,
    912                                                     false);
    913 
    914     // No need to add if the sync promo is already in the startup list.
    915     bool add_promo = true;
    916     for (std::vector<GURL>::const_iterator it = startup_urls->begin();
    917          it != startup_urls->end(); ++it) {
    918       if (*it == sync_promo_url) {
    919         add_promo = false;
    920         break;
    921       }
    922     }
    923 
    924     if (add_promo) {
    925       // If the first URL is the NTP, replace it with the sync promo. This
    926       // behavior is desired because completing or skipping the sync promo
    927       // causes a redirect to the NTP.
    928       if (!startup_urls->empty() &&
    929           startup_urls->at(0) == GURL(chrome::kChromeUINewTabURL))
    930         startup_urls->at(0) = sync_promo_url;
    931       else
    932         startup_urls->insert(startup_urls->begin(), sync_promo_url);
    933     }
    934   }
    935 }
    936