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/app_launch_params.h"
61 #include "chrome/browser/ui/extensions/application_launch.h"
62 #include "chrome/browser/ui/host_desktop.h"
63 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
64 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
65 #include "chrome/browser/ui/startup/default_browser_prompt.h"
66 #include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
67 #include "chrome/browser/ui/startup/obsolete_system_infobar_delegate.h"
68 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
69 #include "chrome/browser/ui/startup/startup_browser_creator.h"
70 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
71 #include "chrome/browser/ui/tabs/tab_strip_model.h"
72 #include "chrome/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/extensions/extension_metrics.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::ASCIIToUTF16(appdata_path
)) != base::string16::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::IsNewBookmarkAppsEnabled() &&
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 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_APP
,
218 void RecordAppLaunches(Profile
* profile
,
219 const std::vector
<GURL
>& cmd_line_urls
,
220 const StartupTabs
& autolaunch_tabs
) {
221 const extensions::ExtensionSet
& extensions
=
222 extensions::ExtensionRegistry::Get(profile
)->enabled_extensions();
223 for (size_t i
= 0; i
< cmd_line_urls
.size(); ++i
) {
224 const extensions::Extension
* extension
=
225 extensions
.GetAppByURL(cmd_line_urls
.at(i
));
227 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_URL
,
228 extension
->GetType());
231 for (size_t i
= 0; i
< autolaunch_tabs
.size(); ++i
) {
232 const extensions::Extension
* extension
=
233 extensions
.GetAppByURL(autolaunch_tabs
.at(i
).url
);
235 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_AUTOLAUNCH
,
236 extension
->GetType());
241 class WebContentsCloseObserver
: public content::NotificationObserver
{
243 WebContentsCloseObserver() : contents_(NULL
) {}
244 ~WebContentsCloseObserver() override
{}
246 void SetContents(content::WebContents
* contents
) {
248 contents_
= contents
;
251 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
252 content::Source
<content::WebContents
>(contents_
));
255 content::WebContents
* contents() { return contents_
; }
258 // content::NotificationObserver overrides:
259 void Observe(int type
,
260 const content::NotificationSource
& source
,
261 const content::NotificationDetails
& details
) override
{
262 DCHECK_EQ(type
, content::NOTIFICATION_WEB_CONTENTS_DESTROYED
);
266 content::WebContents
* contents_
;
267 content::NotificationRegistrar registrar_
;
269 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver
);
272 // TODO(koz): Consolidate this function and remove the special casing.
273 const Extension
* GetPlatformApp(Profile
* profile
,
274 const std::string
& extension_id
) {
275 const Extension
* extension
=
276 extensions::ExtensionRegistry::Get(profile
)->GetExtensionById(
277 extension_id
, extensions::ExtensionRegistry::EVERYTHING
);
278 return extension
&& extension
->is_platform_app() ? extension
: NULL
;
283 namespace internals
{
285 GURL
GetWelcomePageURL() {
286 std::string welcome_url
= l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL
);
287 return GURL(welcome_url
);
290 } // namespace internals
292 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
293 const base::FilePath
& cur_dir
,
294 const base::CommandLine
& command_line
,
295 chrome::startup::IsFirstRun is_first_run
)
297 command_line_(command_line
),
299 browser_creator_(NULL
),
300 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
303 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
304 const base::FilePath
& cur_dir
,
305 const base::CommandLine
& command_line
,
306 StartupBrowserCreator
* browser_creator
,
307 chrome::startup::IsFirstRun is_first_run
)
309 command_line_(command_line
),
311 browser_creator_(browser_creator
),
312 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
315 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
318 bool StartupBrowserCreatorImpl::Launch(Profile
* profile
,
319 const std::vector
<GURL
>& urls_to_open
,
320 bool process_startup
,
321 chrome::HostDesktopType desktop_type
) {
325 if (command_line_
.HasSwitch(switches::kDnsLogDetails
))
326 chrome_browser_net::EnablePredictorDetailedLog(true);
328 if (AppListService::HandleLaunchCommandLine(command_line_
, profile
))
331 if (command_line_
.HasSwitch(switches::kAppId
)) {
332 std::string app_id
= command_line_
.GetSwitchValueASCII(switches::kAppId
);
333 const Extension
* extension
= GetPlatformApp(profile
, app_id
);
334 // If |app_id| is a disabled or terminated platform app we handle it
335 // specially here, otherwise it will be handled below.
337 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP
);
338 AppLaunchParams
params(profile
, extension
,
339 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
,
340 extensions::SOURCE_COMMAND_LINE
);
341 params
.command_line
= command_line_
;
342 params
.current_directory
= cur_dir_
;
343 // If we are being launched from the command line, default to native
345 params
.desktop_type
= chrome::HOST_DESKTOP_TYPE_NATIVE
;
346 OpenApplicationWithReenablePrompt(params
);
351 // Open the required browser windows and tabs. First, see if
352 // we're being run as an application window. If so, the user
353 // opened an app shortcut. Don't restore tabs or open initial
354 // URLs in that case. The user should see the window as an app,
356 // Special case is when app switches are passed but we do want to restore
357 // session. In that case open app window + focus it after session is restored.
358 content::WebContents
* app_contents
= NULL
;
359 if (OpenApplicationWindow(profile
, &app_contents
)) {
360 RecordLaunchModeHistogram(LM_AS_WEBAPP
);
362 RecordLaunchModeHistogram(urls_to_open
.empty() ?
363 LM_TO_BE_DECIDED
: LM_WITH_URLS
);
365 ProcessLaunchURLs(process_startup
, urls_to_open
, desktop_type
);
367 if (command_line_
.HasSwitch(switches::kInstallChromeApp
)) {
368 install_chrome_app::InstallChromeApp(
369 command_line_
.GetSwitchValueASCII(switches::kInstallChromeApp
));
372 // If this is an app launch, but we didn't open an app window, it may
374 OpenApplicationTab(profile
);
376 #if defined(OS_MACOSX)
377 if (process_startup
) {
378 // Check whether the auto-update system needs to be promoted from user
380 KeystoneInfoBar::PromotionInfoBar(profile
);
385 // In kiosk mode, we want to always be fullscreen, so switch to that now.
386 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode
) ||
387 base::CommandLine::ForCurrentProcess()->HasSwitch(
388 switches::kStartFullscreen
)) {
389 // It's possible for there to be no browser window, e.g. if someone
390 // specified a non-sensical combination of options
391 // ("--kiosk --no_startup_window"); do nothing in that case.
392 Browser
* browser
= BrowserList::GetInstance(desktop_type
)->GetLastActive();
394 chrome::ToggleFullscreenMode(browser
);
399 ShellIntegration::MigrateChromiumShortcuts();
400 #endif // defined(OS_WIN)
405 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string
* app_url
,
406 std::string
* app_id
) {
407 if (command_line_
.HasSwitch(switches::kApp
)) {
409 *app_url
= command_line_
.GetSwitchValueASCII(switches::kApp
);
412 if (command_line_
.HasSwitch(switches::kAppId
)) {
414 *app_id
= command_line_
.GetSwitchValueASCII(switches::kAppId
);
420 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile
* profile
) {
422 // App shortcuts to URLs always open in an app window. Because this
423 // function will open an app that should be in a tab, there is no need
424 // to look at the app URL. OpenApplicationWindow() will open app url
426 if (!IsAppLaunch(NULL
, &app_id
) || app_id
.empty())
429 extensions::LaunchContainer launch_container
;
430 const Extension
* extension
;
431 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
434 // If the user doesn't want to open a tab, fail.
435 if (launch_container
!= extensions::LAUNCH_CONTAINER_TAB
)
438 RecordCmdLineAppHistogram(extension
->GetType());
440 WebContents
* app_tab
= OpenApplication(
441 AppLaunchParams(profile
, extension
, extensions::LAUNCH_CONTAINER_TAB
,
442 NEW_FOREGROUND_TAB
, extensions::SOURCE_COMMAND_LINE
));
443 return (app_tab
!= NULL
);
446 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
448 content::WebContents
** out_app_contents
) {
449 // Set |out_app_contents| to NULL early on (just in case).
450 if (out_app_contents
)
451 *out_app_contents
= NULL
;
453 std::string url_string
, app_id
;
454 if (!IsAppLaunch(&url_string
, &app_id
))
457 // This can fail if the app_id is invalid. It can also fail if the
458 // extension is external, and has not yet been installed.
459 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
460 // Open an URL to the gallery page of the extension id?
461 if (!app_id
.empty()) {
462 extensions::LaunchContainer launch_container
;
463 const Extension
* extension
;
464 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
467 // TODO(skerner): Could pass in |extension| and |launch_container|,
468 // and avoid calling GetAppLaunchContainer() both here and in
469 // OpenApplicationTab().
471 if (launch_container
== extensions::LAUNCH_CONTAINER_TAB
)
474 RecordCmdLineAppHistogram(extension
->GetType());
476 AppLaunchParams
params(profile
, extension
, launch_container
, NEW_WINDOW
,
477 extensions::SOURCE_COMMAND_LINE
);
478 params
.command_line
= command_line_
;
479 params
.current_directory
= cur_dir_
;
480 WebContents
* tab_in_app_window
= OpenApplication(params
);
482 if (out_app_contents
)
483 *out_app_contents
= tab_in_app_window
;
485 // Platform apps fire off a launch event which may or may not open a window.
486 return (tab_in_app_window
!= NULL
|| CanLaunchViaEvent(extension
));
489 if (url_string
.empty())
492 #if defined(OS_WIN) // Fix up Windows shortcuts.
493 ReplaceSubstringsAfterOffset(&url_string
, 0, "\\x", "%");
495 GURL
url(url_string
);
497 // Restrict allowed URLs for --app switch.
498 if (!url
.is_empty() && url
.is_valid()) {
499 ChildProcessSecurityPolicy
* policy
=
500 ChildProcessSecurityPolicy::GetInstance();
501 if (policy
->IsWebSafeScheme(url
.scheme()) ||
502 url
.SchemeIs(url::kFileScheme
)) {
503 const extensions::Extension
* extension
=
504 extensions::ExtensionRegistry::Get(profile
)
505 ->enabled_extensions().GetAppByURL(url
);
507 RecordCmdLineAppHistogram(extension
->GetType());
509 extensions::RecordAppLaunchType(
510 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY
,
511 extensions::Manifest::TYPE_HOSTED_APP
);
514 WebContents
* app_tab
= OpenAppShortcutWindow(profile
, url
);
516 if (out_app_contents
)
517 *out_app_contents
= app_tab
;
519 return (app_tab
!= NULL
);
525 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
526 bool process_startup
,
527 const std::vector
<GURL
>& urls_to_open
,
528 chrome::HostDesktopType desktop_type
) {
529 // If we're starting up in "background mode" (no open browser window) then
530 // don't open any browser windows, unless kAutoLaunchAtStartup is also
532 if (process_startup
&&
533 command_line_
.HasSwitch(switches::kNoStartupWindow
) &&
534 !command_line_
.HasSwitch(switches::kAutoLaunchAtStartup
)) {
538 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
540 if (base::win::GetVersion() >= base::win::VERSION_WIN8
) {
541 // See if there are apps for this profile that should be launched on startup
542 // due to a switch from Metro mode.
543 app_metro_launch::HandleAppLaunchForMetroRestart(profile_
);
547 if (process_startup
&& ProcessStartupURLs(urls_to_open
, desktop_type
)) {
548 // ProcessStartupURLs processed the urls, nothing else to do.
552 chrome::startup::IsProcessStartup is_process_startup
= process_startup
?
553 chrome::startup::IS_PROCESS_STARTUP
:
554 chrome::startup::IS_NOT_PROCESS_STARTUP
;
555 if (!process_startup
) {
556 // Even if we're not starting a new process, this may conceptually be
557 // "startup" for the user and so should be handled in a similar way. Eg.,
558 // Chrome may have been running in the background due to an app with a
559 // background page being installed, or running with only an app window
561 SessionService
* service
=
562 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
563 if (service
&& service
->ShouldNewWindowStartSession()) {
564 // Restore the last session if any.
565 if (!HasPendingUncleanExit(profile_
) &&
566 service
->RestoreIfNecessary(urls_to_open
)) {
569 // Open user-specified URLs like pinned tabs and startup tabs.
570 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
, desktop_type
);
572 AddInfoBarsIfNecessary(browser
, is_process_startup
);
578 // Session startup didn't occur, open the urls.
579 Browser
* browser
= NULL
;
580 std::vector
<GURL
> adjust_urls
= urls_to_open
;
581 if (adjust_urls
.empty()) {
582 AddStartupURLs(&adjust_urls
);
583 } else if (!command_line_
.HasSwitch(switches::kOpenInNewWindow
)) {
584 // Always open a list of urls in a window on the native desktop.
585 browser
= chrome::FindTabbedBrowser(profile_
, false,
586 chrome::HOST_DESKTOP_TYPE_NATIVE
);
588 // This will launch a browser; prevent session restore.
589 StartupBrowserCreator::in_synchronous_profile_launch_
= true;
590 browser
= OpenURLsInBrowser(browser
, process_startup
, adjust_urls
,
592 StartupBrowserCreator::in_synchronous_profile_launch_
= false;
593 AddInfoBarsIfNecessary(browser
, is_process_startup
);
596 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
597 const std::vector
<GURL
>& urls_to_open
,
598 chrome::HostDesktopType desktop_type
) {
599 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
600 SessionStartupPref pref
=
601 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
602 if (pref
.type
== SessionStartupPref::LAST
)
603 VLOG(1) << "Pref: last";
604 else if (pref
.type
== SessionStartupPref::URLS
)
605 VLOG(1) << "Pref: urls";
606 else if (pref
.type
== SessionStartupPref::DEFAULT
)
607 VLOG(1) << "Pref: default";
609 apps::AppRestoreService
* restore_service
=
610 apps::AppRestoreServiceFactory::GetForProfile(profile_
);
611 // NULL in incognito mode.
612 if (restore_service
) {
613 restore_service
->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
614 StartupBrowserCreator::WasRestarted()));
617 if (pref
.type
== SessionStartupPref::LAST
) {
618 if (profile_
->GetLastSessionExitType() == Profile::EXIT_CRASHED
&&
619 !command_line_
.HasSwitch(switches::kRestoreLastSession
)) {
620 // The last session crashed. It's possible automatically loading the
621 // page will trigger another crash, locking the user out of chrome.
622 // To avoid this, don't restore on startup but instead show the crashed
624 VLOG(1) << "Unclean exit; not processing";
628 uint32 restore_behavior
= SessionRestore::SYNCHRONOUS
;
629 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore
||
630 base::CommandLine::ForCurrentProcess()->HasSwitch(
631 switches::kCreateBrowserOnStartupForTests
)) {
632 restore_behavior
|= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
635 #if defined(OS_MACOSX)
636 // On Mac, when restoring a session with no windows, suppress the creation
637 // of a new window in the case where the system is launching Chrome via a
638 // login item or Lion's resume feature.
639 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
640 restore_behavior
= restore_behavior
&
641 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
645 // The startup code only executes for browsers launched in desktop mode.
646 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
647 Browser
* browser
= SessionRestore::RestoreSession(
648 profile_
, NULL
, desktop_type
, restore_behavior
,
651 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
655 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
, desktop_type
);
659 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
661 // Session restore may occur if the startup preference is "last" or if the
662 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
663 // to start deleting leftover data.
664 if (pref
.type
!= SessionStartupPref::LAST
&&
665 !HasPendingUncleanExit(profile_
)) {
666 content::BrowserContext::GetDefaultStoragePartition(profile_
)->
667 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
673 Browser
* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
674 const std::vector
<GURL
>& urls_to_open
,
675 chrome::HostDesktopType desktop_type
) {
676 SessionStartupPref pref
=
677 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
679 // Pinned tabs should not be displayed when chrome is launched in incognito
680 // mode. Also, no pages should be opened automatically if the session
681 // crashed. Otherwise it might trigger another crash, locking the user out of
682 // chrome. The crash infobar is shown in this case.
683 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_
,
684 profile_
->GetPrefs()) &&
685 !HasPendingUncleanExit(profile_
)) {
686 tabs
= PinnedTabCodec::ReadPinnedTabs(profile_
);
689 RecordAppLaunches(profile_
, urls_to_open
, tabs
);
691 if (!urls_to_open
.empty()) {
692 // If urls were specified on the command line, use them.
693 UrlsToTabs(urls_to_open
, &tabs
);
694 } else if (pref
.type
== SessionStartupPref::DEFAULT
||
696 browser_creator_
&& !browser_creator_
->first_run_tabs_
.empty())) {
697 std::vector
<GURL
> urls
;
698 AddStartupURLs(&urls
);
699 UrlsToTabs(urls
, &tabs
);
700 } else if (pref
.type
== SessionStartupPref::URLS
&& !pref
.urls
.empty() &&
701 !HasPendingUncleanExit(profile_
)) {
702 // Only use the set of urls specified in preferences if nothing was
703 // specified on the command line. Filter out any urls that are to be
704 // restored by virtue of having been previously pinned.
705 AddUniqueURLs(pref
.urls
, &tabs
);
706 } else if (pref
.type
== SessionStartupPref::HOMEPAGE
) {
707 // If 'homepage' selected, either by the user or by a policy, we should
708 // have migrated them to another value.
709 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
715 Browser
* browser
= OpenTabsInBrowser(NULL
, true, tabs
, desktop_type
);
719 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector
<GURL
>& urls
,
721 size_t num_existing_tabs
= tabs
->size();
722 for (size_t i
= 0; i
< urls
.size(); ++i
) {
723 bool in_tabs
= false;
724 for (size_t j
= 0; j
< num_existing_tabs
; ++j
) {
725 if (urls
[i
] == (*tabs
)[j
].url
) {
732 tab
.is_pinned
= false;
734 tabs
->push_back(tab
);
739 Browser
* StartupBrowserCreatorImpl::OpenURLsInBrowser(
741 bool process_startup
,
742 const std::vector
<GURL
>& urls
,
743 chrome::HostDesktopType desktop_type
) {
745 UrlsToTabs(urls
, &tabs
);
746 return OpenTabsInBrowser(browser
, process_startup
, tabs
, desktop_type
);
749 Browser
* StartupBrowserCreatorImpl::OpenTabsInBrowser(
751 bool process_startup
,
752 const StartupTabs
& tabs
,
753 chrome::HostDesktopType desktop_type
) {
754 DCHECK(!tabs
.empty());
756 // If we don't yet have a profile, try to use the one we're given from
757 // |browser|. While we may not end up actually using |browser| (since it
758 // could be a popup window), we can at least use the profile.
759 if (!profile_
&& browser
)
760 profile_
= browser
->profile();
762 if (!browser
|| !browser
->is_type_tabbed())
763 browser
= new Browser(Browser::CreateParams(profile_
, desktop_type
));
765 bool first_tab
= true;
766 ProtocolHandlerRegistry
* registry
= profile_
?
767 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_
) : NULL
;
768 for (size_t i
= 0; i
< tabs
.size(); ++i
) {
769 // We skip URLs that we'd have to launch an external protocol handler for.
770 // This avoids us getting into an infinite loop asking ourselves to open
771 // a URL, should the handler be (incorrectly) configured to be us. Anyone
772 // asking us to open such a URL should really ask the handler directly.
773 bool handled_by_chrome
= ProfileIOData::IsHandledURL(tabs
[i
].url
) ||
774 (registry
&& registry
->IsHandledProtocol(tabs
[i
].url
.scheme()));
775 if (!process_startup
&& !handled_by_chrome
)
778 int add_types
= first_tab
? TabStripModel::ADD_ACTIVE
:
779 TabStripModel::ADD_NONE
;
780 add_types
|= TabStripModel::ADD_FORCE_INDEX
;
781 if (tabs
[i
].is_pinned
)
782 add_types
|= TabStripModel::ADD_PINNED
;
784 chrome::NavigateParams
params(browser
, tabs
[i
].url
,
785 ui::PAGE_TRANSITION_AUTO_TOPLEVEL
);
786 params
.disposition
= first_tab
? NEW_FOREGROUND_TAB
: NEW_BACKGROUND_TAB
;
787 params
.tabstrip_add_types
= add_types
;
788 params
.extension_app_id
= tabs
[i
].app_id
;
790 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
791 if (process_startup
&& google_util::IsGoogleHomePageUrl(tabs
[i
].url
)) {
792 params
.extra_headers
= RLZTracker::GetAccessPointHttpHeader(
793 RLZTracker::ChromeHomePage());
795 #endif // defined(ENABLE_RLZ) && !defined(OS_IOS)
797 chrome::Navigate(¶ms
);
801 if (!browser
->tab_strip_model()->GetActiveWebContents()) {
802 // TODO: this is a work around for 110909. Figure out why it's needed.
803 if (!browser
->tab_strip_model()->count())
804 chrome::AddTabAt(browser
, GURL(), -1, true);
806 browser
->tab_strip_model()->ActivateTabAt(0, false);
809 // The default behavior is to show the window, as expressed by the default
810 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
811 // to true ahead of this place, it means another task must have been spawned
812 // to take care of that.
813 if (!browser_creator_
|| browser_creator_
->show_main_browser_window())
814 browser
->window()->Show();
819 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
821 chrome::startup::IsProcessStartup is_process_startup
) {
822 if (!browser
|| !profile_
|| browser
->tab_strip_model()->count() == 0)
825 if (HasPendingUncleanExit(browser
->profile()) &&
826 !browser
->window()->ShowSessionCrashedBubble()) {
827 SessionCrashedInfoBarDelegate::Create(browser
);
830 // The below info bars are only added to the first profile which is launched.
831 // Other profiles might be restoring the browsing sessions asynchronously,
832 // so we cannot add the info bars to the focused tabs here.
833 if (is_process_startup
== chrome::startup::IS_PROCESS_STARTUP
&&
834 !command_line_
.HasSwitch(switches::kTestType
)) {
835 chrome::ShowBadFlagsPrompt(browser
);
836 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
837 browser
->tab_strip_model()->GetActiveWebContents()));
838 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
839 browser
->tab_strip_model()->GetActiveWebContents()));
841 #if !defined(OS_CHROMEOS)
842 if (!command_line_
.HasSwitch(switches::kNoDefaultBrowserCheck
)) {
843 // Generally, the default browser prompt should not be shown on first
844 // run. However, when the set-as-default dialog has been suppressed, we
846 if ((!is_first_run_
||
848 browser_creator_
->is_default_browser_dialog_suppressed())) &&
849 !chrome::ShowAutolaunchPrompt(browser
)) {
850 chrome::ShowDefaultBrowserPrompt(profile_
,
851 browser
->host_desktop_type());
858 void StartupBrowserCreatorImpl::AddStartupURLs(
859 std::vector
<GURL
>* startup_urls
) const {
860 // TODO(atwilson): Simplify the logic that decides which tabs to open on
861 // start-up and make it more consistent. http://crbug.com/248883
863 // If we have urls specified by the first run master preferences use them
865 if (browser_creator_
&& startup_urls
->empty()) {
866 if (!browser_creator_
->first_run_tabs_
.empty()) {
867 std::vector
<GURL
>::iterator it
=
868 browser_creator_
->first_run_tabs_
.begin();
869 while (it
!= browser_creator_
->first_run_tabs_
.end()) {
870 // Replace magic names for the actual urls.
871 if (it
->host() == "new_tab_page") {
872 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
873 } else if (it
->host() == "welcome_page") {
874 startup_urls
->push_back(internals::GetWelcomePageURL());
876 startup_urls
->push_back(*it
);
880 browser_creator_
->first_run_tabs_
.clear();
884 // Otherwise open at least the new tab page (and the welcome page, if this
885 // is the first time the browser is being started), or the set of URLs
886 // specified on the command line.
887 if (startup_urls
->empty()) {
888 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
889 if (first_run::ShouldShowWelcomePage())
890 startup_urls
->push_back(internals::GetWelcomePageURL());
893 if (signin::ShouldShowPromoAtStartup(profile_
, is_first_run_
)) {
894 signin::DidShowPromoAtStartup(profile_
);
896 const GURL sync_promo_url
= signin::GetPromoURL(
897 signin_metrics::SOURCE_START_PAGE
, false);
899 // No need to add if the sync promo is already in the startup list.
900 bool add_promo
= true;
901 for (std::vector
<GURL
>::const_iterator it
= startup_urls
->begin();
902 it
!= startup_urls
->end(); ++it
) {
903 if (*it
== sync_promo_url
) {
910 // If the first URL is the NTP, replace it with the sync promo. This
911 // behavior is desired because completing or skipping the sync promo
912 // causes a redirect to the NTP.
913 if (!startup_urls
->empty() &&
914 startup_urls
->at(0) == GURL(chrome::kChromeUINewTabURL
))
915 startup_urls
->at(0) = sync_promo_url
;
917 startup_urls
->insert(startup_urls
->begin(), sync_promo_url
);