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