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.
5 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
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/prefs/pref_service.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "chrome/browser/apps/install_chrome_app.h"
28 #include "chrome/browser/auto_launch_trial.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
32 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
33 #include "chrome/browser/defaults.h"
34 #include "chrome/browser/extensions/extension_creator.h"
35 #include "chrome/browser/extensions/extension_util.h"
36 #include "chrome/browser/extensions/launch_util.h"
37 #include "chrome/browser/extensions/pack_extension_job.h"
38 #include "chrome/browser/first_run/first_run.h"
39 #include "chrome/browser/infobars/infobar_service.h"
40 #include "chrome/browser/net/predictor.h"
41 #include "chrome/browser/notifications/desktop_notification_service.h"
42 #include "chrome/browser/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_system_infobar_delegate.h"
67 #include "chrome/browser/ui/startup/session_crashed_bubble.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/url_constants.h"
80 #include "chrome/grit/locale_settings.h"
81 #include "chrome/installer/util/browser_distribution.h"
82 #include "components/google/core/browser/google_util.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 "extensions/browser/extension_prefs.h"
90 #include "extensions/browser/extension_registry.h"
91 #include "extensions/common/constants.h"
92 #include "extensions/common/extension.h"
93 #include "extensions/common/extension_set.h"
94 #include "ui/base/l10n/l10n_util.h"
96 #if defined(OS_MACOSX)
97 #include "base/mac/mac_util.h"
98 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
102 #include "base/win/windows_version.h"
103 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
106 using content::ChildProcessSecurityPolicy;
107 using content::WebContents;
108 using extensions::Extension;
112 // Utility functions ----------------------------------------------------------
115 LM_TO_BE_DECIDED = 0, // Possibly direct launch or via a shortcut.
116 LM_AS_WEBAPP, // Launched as a installed web application.
117 LM_WITH_URLS, // Launched with urls in the cmd line.
118 LM_SHORTCUT_NONE, // Not launched from a shortcut.
119 LM_SHORTCUT_NONAME, // Launched from shortcut but no name available.
120 LM_SHORTCUT_UNKNOWN, // Launched from user-defined shortcut.
121 LM_SHORTCUT_QUICKLAUNCH, // Launched from the quick launch bar.
122 LM_SHORTCUT_DESKTOP, // Launched from a desktop shortcut.
123 LM_SHORTCUT_TASKBAR, // Launched from the taskbar.
124 LM_LINUX_MAC_BEOS // Other OS buckets start here.
128 // Undocumented flag in the startup info structure tells us what shortcut was
129 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
130 // more information. Confirmed to work on XP, Vista and Win7.
131 LaunchMode GetLaunchShortcutKind() {
132 STARTUPINFOW si = { sizeof(si) };
133 GetStartupInfoW(&si);
134 if (si.dwFlags & 0x800) {
136 return LM_SHORTCUT_NONAME;
137 base::string16 shortcut(si.lpTitle);
138 // The windows quick launch path is not localized.
139 if (shortcut.find(L"\\Quick Launch\\") != base::string16::npos) {
140 if (base::win::GetVersion() >= base::win::VERSION_WIN7)
141 return LM_SHORTCUT_TASKBAR;
143 return LM_SHORTCUT_QUICKLAUNCH;
145 scoped_ptr<base::Environment> env(base::Environment::Create());
146 std::string appdata_path;
147 env->GetVar("USERPROFILE", &appdata_path);
148 if (!appdata_path.empty() &&
149 shortcut.find(base::ASCIIToWide(appdata_path)) != std::wstring::npos)
150 return LM_SHORTCUT_DESKTOP;
151 return LM_SHORTCUT_UNKNOWN;
153 return LM_SHORTCUT_NONE;
156 // TODO(cpu): Port to other platforms.
157 LaunchMode GetLaunchShortcutKind() {
158 return LM_LINUX_MAC_BEOS;
162 // Log in a histogram the frequency of launching by the different methods. See
163 // LaunchMode enum for the actual values of the buckets.
164 void RecordLaunchModeHistogram(LaunchMode mode) {
165 int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
166 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
169 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
170 for (size_t i = 0; i < urls.size(); ++i) {
172 tab.is_pinned = false;
174 tabs->push_back(tab);
178 // Return true if the command line option --app-id is used. Set
179 // |out_extension| to the app to open, and |out_launch_container|
180 // to the type of window into which the app should be open.
181 bool GetAppLaunchContainer(
183 const std::string& app_id,
184 const Extension** out_extension,
185 extensions::LaunchContainer* out_launch_container) {
187 const Extension* extension = extensions::ExtensionRegistry::Get(
188 profile)->enabled_extensions().GetByID(app_id);
189 // The extension with id |app_id| may have been uninstalled.
193 // Don't launch platform apps in incognito mode.
194 if (profile->IsOffTheRecord() && extension->is_platform_app())
197 // Look at preferences to find the right launch container. If no
198 // preference is set, launch as a window.
199 extensions::LaunchContainer launch_container = extensions::GetLaunchContainer(
200 extensions::ExtensionPrefs::Get(profile), extension);
202 if (!extensions::util::IsStreamlinedHostedAppsEnabled() &&
203 !extensions::HasPreferredLaunchContainer(
204 extensions::ExtensionPrefs::Get(profile), extension)) {
205 launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
208 *out_extension = extension;
209 *out_launch_container = launch_container;
213 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
214 CoreAppLauncherHandler::RecordAppLaunchType(
215 extension_misc::APP_LAUNCH_CMD_LINE_APP,
219 void RecordAppLaunches(Profile* profile,
220 const std::vector<GURL>& cmd_line_urls,
221 const StartupTabs& autolaunch_tabs) {
222 const extensions::ExtensionSet& extensions =
223 extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
224 for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
225 const extensions::Extension* extension =
226 extensions.GetAppByURL(cmd_line_urls.at(i));
228 CoreAppLauncherHandler::RecordAppLaunchType(
229 extension_misc::APP_LAUNCH_CMD_LINE_URL,
230 extension->GetType());
233 for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
234 const extensions::Extension* extension =
235 extensions.GetAppByURL(autolaunch_tabs.at(i).url);
237 CoreAppLauncherHandler::RecordAppLaunchType(
238 extension_misc::APP_LAUNCH_AUTOLAUNCH,
239 extension->GetType());
244 class WebContentsCloseObserver : public content::NotificationObserver {
246 WebContentsCloseObserver() : contents_(NULL) {}
247 ~WebContentsCloseObserver() override {}
249 void SetContents(content::WebContents* contents) {
251 contents_ = contents;
254 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
255 content::Source<content::WebContents>(contents_));
258 content::WebContents* contents() { return contents_; }
261 // content::NotificationObserver overrides:
262 void Observe(int type,
263 const content::NotificationSource& source,
264 const content::NotificationDetails& details) override {
265 DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
269 content::WebContents* contents_;
270 content::NotificationRegistrar registrar_;
272 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
275 // TODO(koz): Consolidate this function and remove the special casing.
276 const Extension* GetPlatformApp(Profile* profile,
277 const std::string& extension_id) {
278 const Extension* extension =
279 extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
280 extension_id, extensions::ExtensionRegistry::EVERYTHING);
281 return extension && extension->is_platform_app() ? extension : NULL;
286 namespace internals {
288 GURL GetWelcomePageURL() {
289 std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
290 return GURL(welcome_url);
293 } // namespace internals
295 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
296 const base::FilePath& cur_dir,
297 const CommandLine& command_line,
298 chrome::startup::IsFirstRun is_first_run)
300 command_line_(command_line),
302 browser_creator_(NULL),
303 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
306 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
307 const base::FilePath& cur_dir,
308 const CommandLine& command_line,
309 StartupBrowserCreator* browser_creator,
310 chrome::startup::IsFirstRun is_first_run)
312 command_line_(command_line),
314 browser_creator_(browser_creator),
315 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
318 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
321 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
322 const std::vector<GURL>& urls_to_open,
323 bool process_startup,
324 chrome::HostDesktopType desktop_type) {
328 if (command_line_.HasSwitch(switches::kDnsLogDetails))
329 chrome_browser_net::EnablePredictorDetailedLog(true);
331 if (AppListService::HandleLaunchCommandLine(command_line_, profile))
334 if (command_line_.HasSwitch(switches::kAppId)) {
335 std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
336 const Extension* extension = GetPlatformApp(profile, app_id);
337 // If |app_id| is a disabled or terminated platform app we handle it
338 // specially here, otherwise it will be handled below.
340 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
341 AppLaunchParams params(profile, extension,
342 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW);
343 params.command_line = command_line_;
344 params.current_directory = cur_dir_;
345 // If we are being launched from the command line, default to native
347 params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
348 OpenApplicationWithReenablePrompt(params);
353 // Open the required browser windows and tabs. First, see if
354 // we're being run as an application window. If so, the user
355 // opened an app shortcut. Don't restore tabs or open initial
356 // URLs in that case. The user should see the window as an app,
358 // Special case is when app switches are passed but we do want to restore
359 // session. In that case open app window + focus it after session is restored.
360 content::WebContents* app_contents = NULL;
361 if (OpenApplicationWindow(profile, &app_contents)) {
362 RecordLaunchModeHistogram(LM_AS_WEBAPP);
364 RecordLaunchModeHistogram(urls_to_open.empty() ?
365 LM_TO_BE_DECIDED : LM_WITH_URLS);
367 ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
369 if (command_line_.HasSwitch(switches::kInstallChromeApp)) {
370 install_chrome_app::InstallChromeApp(
371 command_line_.GetSwitchValueASCII(switches::kInstallChromeApp));
374 // If this is an app launch, but we didn't open an app window, it may
376 OpenApplicationTab(profile);
378 #if defined(OS_MACOSX)
379 if (process_startup) {
380 // Check whether the auto-update system needs to be promoted from user
382 KeystoneInfoBar::PromotionInfoBar(profile);
389 ShellIntegration::MigrateChromiumShortcuts();
390 #endif // defined(OS_WIN)
395 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
396 std::string* app_id) {
397 if (command_line_.HasSwitch(switches::kApp)) {
399 *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
402 if (command_line_.HasSwitch(switches::kAppId)) {
404 *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
410 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
412 // App shortcuts to URLs always open in an app window. Because this
413 // function will open an app that should be in a tab, there is no need
414 // to look at the app URL. OpenApplicationWindow() will open app url
416 if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
419 extensions::LaunchContainer launch_container;
420 const Extension* extension;
421 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
424 // If the user doesn't want to open a tab, fail.
425 if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
428 RecordCmdLineAppHistogram(extension->GetType());
430 WebContents* app_tab = OpenApplication(AppLaunchParams(
431 profile, extension, extensions::LAUNCH_CONTAINER_TAB,
432 NEW_FOREGROUND_TAB));
433 return (app_tab != NULL);
436 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
438 content::WebContents** out_app_contents) {
439 // Set |out_app_contents| to NULL early on (just in case).
440 if (out_app_contents)
441 *out_app_contents = NULL;
443 std::string url_string, app_id;
444 if (!IsAppLaunch(&url_string, &app_id))
447 // This can fail if the app_id is invalid. It can also fail if the
448 // extension is external, and has not yet been installed.
449 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
450 // Open an URL to the gallery page of the extension id?
451 if (!app_id.empty()) {
452 extensions::LaunchContainer launch_container;
453 const Extension* extension;
454 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
457 // TODO(skerner): Could pass in |extension| and |launch_container|,
458 // and avoid calling GetAppLaunchContainer() both here and in
459 // OpenApplicationTab().
461 if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
464 RecordCmdLineAppHistogram(extension->GetType());
466 AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW);
467 params.command_line = command_line_;
468 params.current_directory = cur_dir_;
469 WebContents* tab_in_app_window = OpenApplication(params);
471 if (out_app_contents)
472 *out_app_contents = tab_in_app_window;
474 // Platform apps fire off a launch event which may or may not open a window.
475 return (tab_in_app_window != NULL || CanLaunchViaEvent(extension));
478 if (url_string.empty())
481 #if defined(OS_WIN) // Fix up Windows shortcuts.
482 ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
484 GURL url(url_string);
486 // Restrict allowed URLs for --app switch.
487 if (!url.is_empty() && url.is_valid()) {
488 ChildProcessSecurityPolicy* policy =
489 ChildProcessSecurityPolicy::GetInstance();
490 if (policy->IsWebSafeScheme(url.scheme()) ||
491 url.SchemeIs(url::kFileScheme)) {
492 const extensions::Extension* extension =
493 extensions::ExtensionRegistry::Get(profile)
494 ->enabled_extensions().GetAppByURL(url);
496 RecordCmdLineAppHistogram(extension->GetType());
498 CoreAppLauncherHandler::RecordAppLaunchType(
499 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
500 extensions::Manifest::TYPE_HOSTED_APP);
503 WebContents* app_tab = OpenAppShortcutWindow(profile, url);
505 if (out_app_contents)
506 *out_app_contents = app_tab;
508 return (app_tab != NULL);
514 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
515 bool process_startup,
516 const std::vector<GURL>& urls_to_open,
517 chrome::HostDesktopType desktop_type) {
518 // If we're starting up in "background mode" (no open browser window) then
519 // don't open any browser windows, unless kAutoLaunchAtStartup is also
521 if (process_startup &&
522 command_line_.HasSwitch(switches::kNoStartupWindow) &&
523 !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
527 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
529 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
530 // See if there are apps for this profile that should be launched on startup
531 // due to a switch from Metro mode.
532 app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
536 if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
537 // ProcessStartupURLs processed the urls, nothing else to do.
541 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
542 chrome::startup::IS_PROCESS_STARTUP :
543 chrome::startup::IS_NOT_PROCESS_STARTUP;
544 if (!process_startup) {
545 // Even if we're not starting a new process, this may conceptually be
546 // "startup" for the user and so should be handled in a similar way. Eg.,
547 // Chrome may have been running in the background due to an app with a
548 // background page being installed, or running with only an app window
550 SessionService* service =
551 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
552 if (service && service->ShouldNewWindowStartSession()) {
553 // Restore the last session if any.
554 if (!HasPendingUncleanExit(profile_) &&
555 service->RestoreIfNecessary(urls_to_open)) {
558 // Open user-specified URLs like pinned tabs and startup tabs.
559 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
561 AddInfoBarsIfNecessary(browser, is_process_startup);
567 // Session startup didn't occur, open the urls.
568 Browser* browser = NULL;
569 std::vector<GURL> adjust_urls = urls_to_open;
570 if (adjust_urls.empty()) {
571 AddStartupURLs(&adjust_urls);
572 } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
573 // Always open a list of urls in a window on the native desktop.
574 browser = chrome::FindTabbedBrowser(profile_, false,
575 chrome::HOST_DESKTOP_TYPE_NATIVE);
577 // This will launch a browser; prevent session restore.
578 StartupBrowserCreator::in_synchronous_profile_launch_ = true;
579 browser = OpenURLsInBrowser(browser, process_startup, adjust_urls,
581 StartupBrowserCreator::in_synchronous_profile_launch_ = false;
582 AddInfoBarsIfNecessary(browser, is_process_startup);
585 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
586 const std::vector<GURL>& urls_to_open,
587 chrome::HostDesktopType desktop_type) {
588 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
589 SessionStartupPref pref =
590 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
591 if (pref.type == SessionStartupPref::LAST)
592 VLOG(1) << "Pref: last";
593 else if (pref.type == SessionStartupPref::URLS)
594 VLOG(1) << "Pref: urls";
595 else if (pref.type == SessionStartupPref::DEFAULT)
596 VLOG(1) << "Pref: default";
598 apps::AppRestoreService* restore_service =
599 apps::AppRestoreServiceFactory::GetForProfile(profile_);
600 // NULL in incognito mode.
601 if (restore_service) {
602 restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
603 StartupBrowserCreator::WasRestarted()));
606 if (pref.type == SessionStartupPref::LAST) {
607 if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
608 !command_line_.HasSwitch(switches::kRestoreLastSession)) {
609 // The last session crashed. It's possible automatically loading the
610 // page will trigger another crash, locking the user out of chrome.
611 // To avoid this, don't restore on startup but instead show the crashed
613 VLOG(1) << "Unclean exit; not processing";
617 uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
618 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
619 CommandLine::ForCurrentProcess()->HasSwitch(
620 switches::kCreateBrowserOnStartupForTests)) {
621 restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
624 #if defined(OS_MACOSX)
625 // On Mac, when restoring a session with no windows, suppress the creation
626 // of a new window in the case where the system is launching Chrome via a
627 // login item or Lion's resume feature.
628 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
629 restore_behavior = restore_behavior &
630 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
634 // The startup code only executes for browsers launched in desktop mode.
635 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
636 Browser* browser = SessionRestore::RestoreSession(
637 profile_, NULL, desktop_type, restore_behavior,
640 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
644 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
648 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
650 // Session restore may occur if the startup preference is "last" or if the
651 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
652 // to start deleting leftover data.
653 if (pref.type != SessionStartupPref::LAST &&
654 !HasPendingUncleanExit(profile_)) {
655 content::BrowserContext::GetDefaultStoragePartition(profile_)->
656 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
662 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
663 const std::vector<GURL>& urls_to_open,
664 chrome::HostDesktopType desktop_type) {
665 SessionStartupPref pref =
666 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
668 // Pinned tabs should not be displayed when chrome is launched in incognito
669 // mode. Also, no pages should be opened automatically if the session
670 // crashed. Otherwise it might trigger another crash, locking the user out of
671 // chrome. The crash infobar is shown in this case.
672 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
673 profile_->GetPrefs()) &&
674 !HasPendingUncleanExit(profile_)) {
675 tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
678 RecordAppLaunches(profile_, urls_to_open, tabs);
680 if (!urls_to_open.empty()) {
681 // If urls were specified on the command line, use them.
682 UrlsToTabs(urls_to_open, &tabs);
683 } else if (pref.type == SessionStartupPref::DEFAULT ||
685 browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
686 std::vector<GURL> urls;
687 AddStartupURLs(&urls);
688 UrlsToTabs(urls, &tabs);
689 } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
690 !HasPendingUncleanExit(profile_)) {
691 // Only use the set of urls specified in preferences if nothing was
692 // specified on the command line. Filter out any urls that are to be
693 // restored by virtue of having been previously pinned.
694 AddUniqueURLs(pref.urls, &tabs);
695 } else if (pref.type == SessionStartupPref::HOMEPAGE) {
696 // If 'homepage' selected, either by the user or by a policy, we should
697 // have migrated them to another value.
698 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
704 Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
708 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
710 size_t num_existing_tabs = tabs->size();
711 for (size_t i = 0; i < urls.size(); ++i) {
712 bool in_tabs = false;
713 for (size_t j = 0; j < num_existing_tabs; ++j) {
714 if (urls[i] == (*tabs)[j].url) {
721 tab.is_pinned = false;
723 tabs->push_back(tab);
728 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
730 bool process_startup,
731 const std::vector<GURL>& urls,
732 chrome::HostDesktopType desktop_type) {
734 UrlsToTabs(urls, &tabs);
735 return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
738 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
740 bool process_startup,
741 const StartupTabs& tabs,
742 chrome::HostDesktopType desktop_type) {
743 DCHECK(!tabs.empty());
745 // If we don't yet have a profile, try to use the one we're given from
746 // |browser|. While we may not end up actually using |browser| (since it
747 // could be a popup window), we can at least use the profile.
748 if (!profile_ && browser)
749 profile_ = browser->profile();
751 if (!browser || !browser->is_type_tabbed())
752 browser = new Browser(Browser::CreateParams(profile_, desktop_type));
754 bool first_tab = true;
755 ProtocolHandlerRegistry* registry = profile_ ?
756 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_) : NULL;
757 for (size_t i = 0; i < tabs.size(); ++i) {
758 // We skip URLs that we'd have to launch an external protocol handler for.
759 // This avoids us getting into an infinite loop asking ourselves to open
760 // a URL, should the handler be (incorrectly) configured to be us. Anyone
761 // asking us to open such a URL should really ask the handler directly.
762 bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
763 (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
764 if (!process_startup && !handled_by_chrome)
767 int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
768 TabStripModel::ADD_NONE;
769 add_types |= TabStripModel::ADD_FORCE_INDEX;
770 if (tabs[i].is_pinned)
771 add_types |= TabStripModel::ADD_PINNED;
773 chrome::NavigateParams params(browser, tabs[i].url,
774 ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
775 params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
776 params.tabstrip_add_types = add_types;
777 params.extension_app_id = tabs[i].app_id;
779 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
780 if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
781 params.extra_headers = RLZTracker::GetAccessPointHttpHeader(
782 RLZTracker::ChromeHomePage());
784 #endif // defined(ENABLE_RLZ) && !defined(OS_IOS)
786 chrome::Navigate(¶ms);
790 if (!browser->tab_strip_model()->GetActiveWebContents()) {
791 // TODO: this is a work around for 110909. Figure out why it's needed.
792 if (!browser->tab_strip_model()->count())
793 chrome::AddTabAt(browser, GURL(), -1, true);
795 browser->tab_strip_model()->ActivateTabAt(0, false);
798 // The default behavior is to show the window, as expressed by the default
799 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
800 // to true ahead of this place, it means another task must have been spawned
801 // to take care of that.
802 if (!browser_creator_ || browser_creator_->show_main_browser_window())
803 browser->window()->Show();
805 // In kiosk mode, we want to always be fullscreen, so switch to that now.
806 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
807 CommandLine::ForCurrentProcess()->HasSwitch(switches::kStartFullscreen))
808 chrome::ToggleFullscreenMode(browser);
813 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
815 chrome::startup::IsProcessStartup is_process_startup) {
816 if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
819 if (HasPendingUncleanExit(browser->profile()) &&
820 !ShowSessionCrashedBubble(browser)) {
821 SessionCrashedInfoBarDelegate::Create(browser);
824 // The below info bars are only added to the first profile which is launched.
825 // Other profiles might be restoring the browsing sessions asynchronously,
826 // so we cannot add the info bars to the focused tabs here.
827 if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP &&
828 !command_line_.HasSwitch(switches::kTestType)) {
829 chrome::ShowBadFlagsPrompt(browser);
830 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
831 browser->tab_strip_model()->GetActiveWebContents()));
832 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
833 browser->tab_strip_model()->GetActiveWebContents()));
835 #if !defined(OS_CHROMEOS)
836 if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
837 // Generally, the default browser prompt should not be shown on first
838 // run. However, when the set-as-default dialog has been suppressed, we
840 if ((!is_first_run_ ||
842 browser_creator_->is_default_browser_dialog_suppressed())) &&
843 !chrome::ShowAutolaunchPrompt(browser)) {
844 chrome::ShowDefaultBrowserPrompt(profile_,
845 browser->host_desktop_type());
852 void StartupBrowserCreatorImpl::AddStartupURLs(
853 std::vector<GURL>* startup_urls) const {
854 // TODO(atwilson): Simplify the logic that decides which tabs to open on
855 // start-up and make it more consistent. http://crbug.com/248883
857 // If we have urls specified by the first run master preferences use them
859 if (browser_creator_ && startup_urls->empty()) {
860 if (!browser_creator_->first_run_tabs_.empty()) {
861 std::vector<GURL>::iterator it =
862 browser_creator_->first_run_tabs_.begin();
863 while (it != browser_creator_->first_run_tabs_.end()) {
864 // Replace magic names for the actual urls.
865 if (it->host() == "new_tab_page") {
866 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
867 } else if (it->host() == "welcome_page") {
868 startup_urls->push_back(internals::GetWelcomePageURL());
870 startup_urls->push_back(*it);
874 browser_creator_->first_run_tabs_.clear();
878 // Otherwise open at least the new tab page (and the welcome page, if this
879 // is the first time the browser is being started), or the set of URLs
880 // specified on the command line.
881 if (startup_urls->empty()) {
882 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
883 if (first_run::ShouldShowWelcomePage())
884 startup_urls->push_back(internals::GetWelcomePageURL());
887 if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
888 signin::DidShowPromoAtStartup(profile_);
890 const GURL sync_promo_url = signin::GetPromoURL(signin::SOURCE_START_PAGE,
893 // No need to add if the sync promo is already in the startup list.
894 bool add_promo = true;
895 for (std::vector<GURL>::const_iterator it = startup_urls->begin();
896 it != startup_urls->end(); ++it) {
897 if (*it == sync_promo_url) {
904 // If the first URL is the NTP, replace it with the sync promo. This
905 // behavior is desired because completing or skipping the sync promo
906 // causes a redirect to the NTP.
907 if (!startup_urls->empty() &&
908 startup_urls->at(0) == GURL(chrome::kChromeUINewTabURL))
909 startup_urls->at(0) = sync_promo_url;
911 startup_urls->insert(startup_urls->begin(), sync_promo_url);