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