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