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