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/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/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/google/google_util.h"
40 #include "chrome/browser/infobars/infobar_service.h"
41 #include "chrome/browser/net/predictor.h"
42 #include "chrome/browser/notifications/desktop_notification_service.h"
43 #include "chrome/browser/performance_monitor/startup_timer.h"
44 #include "chrome/browser/prefs/incognito_mode_prefs.h"
45 #include "chrome/browser/prefs/session_startup_pref.h"
46 #include "chrome/browser/profiles/profile.h"
47 #include "chrome/browser/profiles/profile_io_data.h"
48 #include "chrome/browser/rlz/rlz.h"
49 #include "chrome/browser/sessions/session_restore.h"
50 #include "chrome/browser/sessions/session_service.h"
51 #include "chrome/browser/sessions/session_service_factory.h"
52 #include "chrome/browser/shell_integration.h"
53 #include "chrome/browser/signin/signin_promo.h"
54 #include "chrome/browser/ui/app_list/app_list_service.h"
55 #include "chrome/browser/ui/browser_commands.h"
56 #include "chrome/browser/ui/browser_finder.h"
57 #include "chrome/browser/ui/browser_list.h"
58 #include "chrome/browser/ui/browser_navigator.h"
59 #include "chrome/browser/ui/browser_tabrestore.h"
60 #include "chrome/browser/ui/browser_tabstrip.h"
61 #include "chrome/browser/ui/browser_window.h"
62 #include "chrome/browser/ui/extensions/application_launch.h"
63 #include "chrome/browser/ui/host_desktop.h"
64 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
65 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
66 #include "chrome/browser/ui/startup/default_browser_prompt.h"
67 #include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
68 #include "chrome/browser/ui/startup/obsolete_system_infobar_delegate.h"
69 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
70 #include "chrome/browser/ui/startup/startup_browser_creator.h"
71 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
72 #include "chrome/browser/ui/tabs/tab_strip_model.h"
73 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
74 #include "chrome/common/chrome_constants.h"
75 #include "chrome/common/chrome_paths.h"
76 #include "chrome/common/chrome_result_codes.h"
77 #include "chrome/common/chrome_switches.h"
78 #include "chrome/common/chrome_version_info.h"
79 #include "chrome/common/extensions/extension_constants.h"
80 #include "chrome/common/net/url_fixer_upper.h"
81 #include "chrome/common/pref_names.h"
82 #include "chrome/common/url_constants.h"
83 #include "chrome/installer/util/browser_distribution.h"
84 #include "content/public/browser/child_process_security_policy.h"
85 #include "content/public/browser/dom_storage_context.h"
86 #include "content/public/browser/notification_observer.h"
87 #include "content/public/browser/notification_registrar.h"
88 #include "content/public/browser/storage_partition.h"
89 #include "content/public/browser/web_contents.h"
90 #include "content/public/browser/web_contents_view.h"
91 #include "extensions/common/constants.h"
92 #include "grit/locale_settings.h"
93 #include "ui/base/l10n/l10n_util.h"
94 #include "ui/base/resource/resource_bundle.h"
95 #include "ui/gfx/rect.h"
96 #include "ui/gfx/screen.h"
98 #if defined(OS_MACOSX)
99 #include "base/mac/mac_util.h"
100 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
103 #if defined(TOOLKIT_GTK)
104 #include "chrome/browser/ui/gtk/gtk_util.h"
108 #include "base/win/windows_version.h"
109 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
112 using content::ChildProcessSecurityPolicy
;
113 using content::WebContents
;
114 using extensions::Extension
;
118 // Utility functions ----------------------------------------------------------
121 LM_TO_BE_DECIDED
= 0, // Possibly direct launch or via a shortcut.
122 LM_AS_WEBAPP
, // Launched as a installed web application.
123 LM_WITH_URLS
, // Launched with urls in the cmd line.
124 LM_SHORTCUT_NONE
, // Not launched from a shortcut.
125 LM_SHORTCUT_NONAME
, // Launched from shortcut but no name available.
126 LM_SHORTCUT_UNKNOWN
, // Launched from user-defined shortcut.
127 LM_SHORTCUT_QUICKLAUNCH
, // Launched from the quick launch bar.
128 LM_SHORTCUT_DESKTOP
, // Launched from a desktop shortcut.
129 LM_SHORTCUT_TASKBAR
, // Launched from the taskbar.
130 LM_LINUX_MAC_BEOS
// Other OS buckets start here.
134 // Undocumented flag in the startup info structure tells us what shortcut was
135 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
136 // more information. Confirmed to work on XP, Vista and Win7.
137 LaunchMode
GetLaunchShortcutKind() {
138 STARTUPINFOW si
= { sizeof(si
) };
139 GetStartupInfoW(&si
);
140 if (si
.dwFlags
& 0x800) {
142 return LM_SHORTCUT_NONAME
;
143 base::string16
shortcut(si
.lpTitle
);
144 // The windows quick launch path is not localized.
145 if (shortcut
.find(L
"\\Quick Launch\\") != base::string16::npos
) {
146 if (base::win::GetVersion() >= base::win::VERSION_WIN7
)
147 return LM_SHORTCUT_TASKBAR
;
149 return LM_SHORTCUT_QUICKLAUNCH
;
151 scoped_ptr
<base::Environment
> env(base::Environment::Create());
152 std::string appdata_path
;
153 env
->GetVar("USERPROFILE", &appdata_path
);
154 if (!appdata_path
.empty() &&
155 shortcut
.find(base::ASCIIToWide(appdata_path
)) != std::wstring::npos
)
156 return LM_SHORTCUT_DESKTOP
;
157 return LM_SHORTCUT_UNKNOWN
;
159 return LM_SHORTCUT_NONE
;
162 // TODO(cpu): Port to other platforms.
163 LaunchMode
GetLaunchShortcutKind() {
164 return LM_LINUX_MAC_BEOS
;
168 // Log in a histogram the frequency of launching by the different methods. See
169 // LaunchMode enum for the actual values of the buckets.
170 void RecordLaunchModeHistogram(LaunchMode mode
) {
171 int bucket
= (mode
== LM_TO_BE_DECIDED
) ? GetLaunchShortcutKind() : mode
;
172 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket
);
175 void UrlsToTabs(const std::vector
<GURL
>& urls
, StartupTabs
* tabs
) {
176 for (size_t i
= 0; i
< urls
.size(); ++i
) {
178 tab
.is_pinned
= false;
180 tabs
->push_back(tab
);
184 // Return true if the command line option --app-id is used. Set
185 // |out_extension| to the app to open, and |out_launch_container|
186 // to the type of window into which the app should be open.
187 bool GetAppLaunchContainer(
189 const std::string
& app_id
,
190 const Extension
** out_extension
,
191 extensions::LaunchContainer
* out_launch_container
) {
193 ExtensionService
* extensions_service
= profile
->GetExtensionService();
194 const Extension
* extension
=
195 extensions_service
->GetExtensionById(app_id
, false);
196 // The extension with id |app_id| may have been uninstalled.
200 // Don't launch platform apps in incognito mode.
201 if (profile
->IsOffTheRecord() && extension
->is_platform_app())
204 // Look at preferences to find the right launch container. If no
205 // preference is set, launch as a window.
206 extensions::LaunchContainer launch_container
= extensions::GetLaunchContainer(
207 extensions_service
->extension_prefs(), extension
);
209 if (!CommandLine::ForCurrentProcess()->HasSwitch(
210 switches::kEnableStreamlinedHostedApps
) &&
211 !extensions::HasPreferredLaunchContainer(
212 extensions_service
->extension_prefs(), extension
)) {
213 launch_container
= extensions::LAUNCH_CONTAINER_WINDOW
;
216 *out_extension
= extension
;
217 *out_launch_container
= launch_container
;
221 // Parse two comma-separated integers from string. Return true on success.
222 bool ParseCommaSeparatedIntegers(const std::string
& str
,
225 std::vector
<std::string
> dimensions
;
226 base::SplitString(str
, ',', &dimensions
);
227 if (dimensions
.size() != 2)
231 if (!base::StringToInt(dimensions
[0], &num1
) ||
232 !base::StringToInt(dimensions
[1], &num2
))
240 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type
) {
241 CoreAppLauncherHandler::RecordAppLaunchType(
242 extension_misc::APP_LAUNCH_CMD_LINE_APP
,
246 void RecordAppLaunches(Profile
* profile
,
247 const std::vector
<GURL
>& cmd_line_urls
,
248 StartupTabs
& autolaunch_tabs
) {
249 ExtensionService
* extension_service
= profile
->GetExtensionService();
250 DCHECK(extension_service
);
251 for (size_t i
= 0; i
< cmd_line_urls
.size(); ++i
) {
252 const extensions::Extension
* extension
=
253 extension_service
->GetInstalledApp(cmd_line_urls
.at(i
));
255 CoreAppLauncherHandler::RecordAppLaunchType(
256 extension_misc::APP_LAUNCH_CMD_LINE_URL
,
257 extension
->GetType());
260 for (size_t i
= 0; i
< autolaunch_tabs
.size(); ++i
) {
261 const extensions::Extension
* extension
=
262 extension_service
->GetInstalledApp(autolaunch_tabs
.at(i
).url
);
264 CoreAppLauncherHandler::RecordAppLaunchType(
265 extension_misc::APP_LAUNCH_AUTOLAUNCH
,
266 extension
->GetType());
271 bool IsNewTabURL(Profile
* profile
, const GURL
& url
) {
272 GURL
ntp_url(chrome::kChromeUINewTabURL
);
273 return url
== ntp_url
||
274 (url
.is_empty() && profile
->GetHomePage() == ntp_url
);
277 class WebContentsCloseObserver
: public content::NotificationObserver
{
279 WebContentsCloseObserver() : contents_(NULL
) {}
280 virtual ~WebContentsCloseObserver() {}
282 void SetContents(content::WebContents
* contents
) {
284 contents_
= contents
;
287 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
288 content::Source
<content::WebContents
>(contents_
));
291 content::WebContents
* contents() { return contents_
; }
294 // content::NotificationObserver overrides:
295 virtual void Observe(int type
,
296 const content::NotificationSource
& source
,
297 const content::NotificationDetails
& details
) OVERRIDE
{
298 DCHECK_EQ(type
, content::NOTIFICATION_WEB_CONTENTS_DESTROYED
);
302 content::WebContents
* contents_
;
303 content::NotificationRegistrar registrar_
;
305 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver
);
308 const Extension
* GetDisabledPlatformApp(Profile
* profile
,
309 const std::string
& extension_id
) {
310 ExtensionService
* service
=
311 extensions::ExtensionSystem::Get(profile
)->extension_service();
312 const Extension
* extension
= service
->GetExtensionById(extension_id
, true);
313 return extension
&& extension
->is_platform_app() ? extension
: NULL
;
318 namespace internals
{
320 GURL
GetWelcomePageURL() {
321 std::string welcome_url
= l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL
);
322 return GURL(welcome_url
);
325 } // namespace internals
327 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
328 const base::FilePath
& cur_dir
,
329 const CommandLine
& command_line
,
330 chrome::startup::IsFirstRun is_first_run
)
332 command_line_(command_line
),
334 browser_creator_(NULL
),
335 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
338 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
339 const base::FilePath
& cur_dir
,
340 const CommandLine
& command_line
,
341 StartupBrowserCreator
* browser_creator
,
342 chrome::startup::IsFirstRun is_first_run
)
344 command_line_(command_line
),
346 browser_creator_(browser_creator
),
347 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
350 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
353 bool StartupBrowserCreatorImpl::Launch(Profile
* profile
,
354 const std::vector
<GURL
>& urls_to_open
,
355 bool process_startup
,
356 chrome::HostDesktopType desktop_type
) {
360 if (command_line_
.HasSwitch(switches::kDnsLogDetails
))
361 chrome_browser_net::EnablePredictorDetailedLog(true);
362 if (command_line_
.HasSwitch(switches::kDnsPrefetchDisable
) &&
363 profile
->GetNetworkPredictor()) {
364 profile
->GetNetworkPredictor()->EnablePredictor(false);
367 AppListService::InitAll(profile
);
368 if (command_line_
.HasSwitch(switches::kAppId
)) {
369 std::string app_id
= command_line_
.GetSwitchValueASCII(switches::kAppId
);
370 const Extension
* extension
= GetDisabledPlatformApp(profile
, app_id
);
371 // If |app_id| is a disabled platform app we handle it specially here,
372 // otherwise it will be handled below.
374 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP
);
375 AppLaunchParams
params(profile
, extension
,
376 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
);
377 params
.command_line
= command_line_
;
378 params
.current_directory
= cur_dir_
;
379 // If we are being launched from the command line, default to native
381 params
.desktop_type
= chrome::HOST_DESKTOP_TYPE_NATIVE
;
382 OpenApplicationWithReenablePrompt(params
);
385 } else if (command_line_
.HasSwitch(switches::kShowAppList
)) {
386 // This switch is used for shortcuts on the native desktop.
387 AppListService::RecordShowTimings(command_line_
);
388 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE
)->
389 ShowForProfile(profile
);
393 // Open the required browser windows and tabs. First, see if
394 // we're being run as an application window. If so, the user
395 // opened an app shortcut. Don't restore tabs or open initial
396 // URLs in that case. The user should see the window as an app,
398 // Special case is when app switches are passed but we do want to restore
399 // session. In that case open app window + focus it after session is restored.
400 content::WebContents
* app_contents
= NULL
;
401 if (OpenApplicationWindow(profile
, &app_contents
)) {
402 RecordLaunchModeHistogram(LM_AS_WEBAPP
);
404 RecordLaunchModeHistogram(urls_to_open
.empty() ?
405 LM_TO_BE_DECIDED
: LM_WITH_URLS
);
407 ProcessLaunchURLs(process_startup
, urls_to_open
, desktop_type
);
409 // If this is an app launch, but we didn't open an app window, it may
411 OpenApplicationTab(profile
);
413 #if defined(OS_MACOSX)
414 if (process_startup
) {
415 // Check whether the auto-update system needs to be promoted from user
417 KeystoneInfoBar::PromotionInfoBar(profile
);
424 ShellIntegration::MigrateChromiumShortcuts();
425 #endif // defined(OS_WIN)
430 void StartupBrowserCreatorImpl::ExtractOptionalAppWindowSize(
432 if (command_line_
.HasSwitch(switches::kAppWindowSize
)) {
435 std::string switch_value
=
436 command_line_
.GetSwitchValueASCII(switches::kAppWindowSize
);
437 if (ParseCommaSeparatedIntegers(switch_value
, &width
, &height
)) {
438 // TODO(scottmg): NativeScreen might be wrong. http://crbug.com/133312
439 const gfx::Rect work_area
=
440 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().work_area();
441 width
= std::min(width
, work_area
.width());
442 height
= std::min(height
, work_area
.height());
443 bounds
->set_size(gfx::Size(width
, height
));
444 bounds
->set_x((work_area
.width() - bounds
->width()) / 2);
445 // TODO(nkostylev): work_area does include launcher but should not.
446 // Launcher auto hide pref is synced and is most likely not applied here.
447 bounds
->set_y((work_area
.height() - bounds
->height()) / 2);
452 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string
* app_url
,
453 std::string
* app_id
) {
454 if (command_line_
.HasSwitch(switches::kApp
)) {
456 *app_url
= command_line_
.GetSwitchValueASCII(switches::kApp
);
459 if (command_line_
.HasSwitch(switches::kAppId
)) {
461 *app_id
= command_line_
.GetSwitchValueASCII(switches::kAppId
);
467 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile
* profile
) {
469 // App shortcuts to URLs always open in an app window. Because this
470 // function will open an app that should be in a tab, there is no need
471 // to look at the app URL. OpenApplicationWindow() will open app url
473 if (!IsAppLaunch(NULL
, &app_id
) || app_id
.empty())
476 extensions::LaunchContainer launch_container
;
477 const Extension
* extension
;
478 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
481 // If the user doesn't want to open a tab, fail.
482 if (launch_container
!= extensions::LAUNCH_CONTAINER_TAB
)
485 RecordCmdLineAppHistogram(extension
->GetType());
487 WebContents
* app_tab
= OpenApplication(AppLaunchParams(
488 profile
, extension
, extensions::LAUNCH_CONTAINER_TAB
,
489 NEW_FOREGROUND_TAB
));
490 return (app_tab
!= NULL
);
493 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
495 content::WebContents
** out_app_contents
) {
496 // Set |out_app_contents| to NULL early on (just in case).
497 if (out_app_contents
)
498 *out_app_contents
= NULL
;
500 std::string url_string
, app_id
;
501 if (!IsAppLaunch(&url_string
, &app_id
))
504 // This can fail if the app_id is invalid. It can also fail if the
505 // extension is external, and has not yet been installed.
506 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
507 // Open an URL to the gallery page of the extension id?
508 if (!app_id
.empty()) {
509 extensions::LaunchContainer launch_container
;
510 const Extension
* extension
;
511 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
514 // TODO(skerner): Could pass in |extension| and |launch_container|,
515 // and avoid calling GetAppLaunchContainer() both here and in
516 // OpenApplicationTab().
518 if (launch_container
== extensions::LAUNCH_CONTAINER_TAB
)
521 RecordCmdLineAppHistogram(extension
->GetType());
523 AppLaunchParams
params(profile
, extension
, launch_container
, NEW_WINDOW
);
524 params
.command_line
= command_line_
;
525 params
.current_directory
= cur_dir_
;
526 WebContents
* tab_in_app_window
= OpenApplication(params
);
528 if (out_app_contents
)
529 *out_app_contents
= tab_in_app_window
;
531 // Platform apps fire off a launch event which may or may not open a window.
532 return (tab_in_app_window
!= NULL
|| extension
->is_platform_app());
535 if (url_string
.empty())
538 #if defined(OS_WIN) // Fix up Windows shortcuts.
539 ReplaceSubstringsAfterOffset(&url_string
, 0, "\\x", "%");
541 GURL
url(url_string
);
543 // Restrict allowed URLs for --app switch.
544 if (!url
.is_empty() && url
.is_valid()) {
545 ChildProcessSecurityPolicy
* policy
=
546 ChildProcessSecurityPolicy::GetInstance();
547 if (policy
->IsWebSafeScheme(url
.scheme()) ||
548 url
.SchemeIs(content::kFileScheme
)) {
549 const extensions::Extension
* extension
=
550 profile
->GetExtensionService()->GetInstalledApp(url
);
552 RecordCmdLineAppHistogram(extension
->GetType());
554 CoreAppLauncherHandler::RecordAppLaunchType(
555 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY
,
556 extensions::Manifest::TYPE_HOSTED_APP
);
559 gfx::Rect override_bounds
;
560 ExtractOptionalAppWindowSize(&override_bounds
);
562 WebContents
* app_tab
= OpenAppShortcutWindow(profile
,
566 if (out_app_contents
)
567 *out_app_contents
= app_tab
;
569 return (app_tab
!= NULL
);
575 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
576 bool process_startup
,
577 const std::vector
<GURL
>& urls_to_open
,
578 chrome::HostDesktopType desktop_type
) {
579 // If we're starting up in "background mode" (no open browser window) then
580 // don't open any browser windows, unless kAutoLaunchAtStartup is also
582 if (process_startup
&&
583 command_line_
.HasSwitch(switches::kNoStartupWindow
) &&
584 !command_line_
.HasSwitch(switches::kAutoLaunchAtStartup
)) {
588 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
590 if (base::win::GetVersion() >= base::win::VERSION_WIN8
) {
591 // See if there are apps for this profile that should be launched on startup
592 // due to a switch from Metro mode.
593 app_metro_launch::HandleAppLaunchForMetroRestart(profile_
);
597 if (process_startup
&& ProcessStartupURLs(urls_to_open
, desktop_type
)) {
598 // ProcessStartupURLs processed the urls, nothing else to do.
602 chrome::startup::IsProcessStartup is_process_startup
= process_startup
?
603 chrome::startup::IS_PROCESS_STARTUP
:
604 chrome::startup::IS_NOT_PROCESS_STARTUP
;
605 if (!process_startup
) {
606 // Even if we're not starting a new process, this may conceptually be
607 // "startup" for the user and so should be handled in a similar way. Eg.,
608 // Chrome may have been running in the background due to an app with a
609 // background page being installed, or running with only an app window
611 SessionService
* service
=
612 SessionServiceFactory::GetForProfileForSessionRestore(profile_
);
613 if (service
&& service
->ShouldNewWindowStartSession()) {
614 // Restore the last session if any.
615 if (!HasPendingUncleanExit(profile_
) &&
616 service
->RestoreIfNecessary(urls_to_open
)) {
619 // Open user-specified URLs like pinned tabs and startup tabs.
620 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
, desktop_type
);
622 AddInfoBarsIfNecessary(browser
, is_process_startup
);
628 // Session startup didn't occur, open the urls.
629 Browser
* browser
= NULL
;
630 std::vector
<GURL
> adjust_urls
= urls_to_open
;
631 if (adjust_urls
.empty()) {
632 AddStartupURLs(&adjust_urls
);
633 if (StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
634 profile_
, adjust_urls
))
636 } else if (!command_line_
.HasSwitch(switches::kOpenInNewWindow
)) {
637 // Always open a list of urls in a window on the native desktop.
638 browser
= chrome::FindTabbedBrowser(profile_
, false,
639 chrome::HOST_DESKTOP_TYPE_NATIVE
);
641 // This will launch a browser; prevent session restore.
642 StartupBrowserCreator::in_synchronous_profile_launch_
= true;
643 browser
= OpenURLsInBrowser(browser
, process_startup
, adjust_urls
,
645 StartupBrowserCreator::in_synchronous_profile_launch_
= false;
646 AddInfoBarsIfNecessary(browser
, is_process_startup
);
649 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
650 const std::vector
<GURL
>& urls_to_open
,
651 chrome::HostDesktopType desktop_type
) {
652 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
653 SessionStartupPref pref
=
654 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
655 if (pref
.type
== SessionStartupPref::LAST
)
656 VLOG(1) << "Pref: last";
657 else if (pref
.type
== SessionStartupPref::URLS
)
658 VLOG(1) << "Pref: urls";
659 else if (pref
.type
== SessionStartupPref::DEFAULT
)
660 VLOG(1) << "Pref: default";
662 apps::AppRestoreService
* restore_service
=
663 apps::AppRestoreServiceFactory::GetForProfile(profile_
);
664 // NULL in incognito mode.
665 if (restore_service
) {
666 restore_service
->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
667 StartupBrowserCreator::WasRestarted()));
670 if (pref
.type
== SessionStartupPref::LAST
) {
671 if (profile_
->GetLastSessionExitType() == Profile::EXIT_CRASHED
&&
672 !command_line_
.HasSwitch(switches::kRestoreLastSession
)) {
673 // The last session crashed. It's possible automatically loading the
674 // page will trigger another crash, locking the user out of chrome.
675 // To avoid this, don't restore on startup but instead show the crashed
677 VLOG(1) << "Unclean exit; not processing";
681 uint32 restore_behavior
= SessionRestore::SYNCHRONOUS
;
682 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore
||
683 CommandLine::ForCurrentProcess()->HasSwitch(
684 switches::kCreateBrowserOnStartupForTests
)) {
685 restore_behavior
|= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
688 #if defined(OS_MACOSX)
689 // On Mac, when restoring a session with no windows, suppress the creation
690 // of a new window in the case where the system is launching Chrome via a
691 // login item or Lion's resume feature.
692 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
693 restore_behavior
= restore_behavior
&
694 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
698 // Pause the StartupTimer. Since the restore here is synchronous, we can
699 // keep these two metrics (browser startup time and session restore time)
701 performance_monitor::StartupTimer::PauseTimer();
703 // The startup code only executes for browsers launched in desktop mode.
704 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
705 Browser
* browser
= SessionRestore::RestoreSession(
706 profile_
, NULL
, desktop_type
, restore_behavior
,
709 performance_monitor::StartupTimer::UnpauseTimer();
711 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
715 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
, desktop_type
);
719 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
721 // Session restore may occur if the startup preference is "last" or if the
722 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
723 // to start deleting leftover data.
724 if (pref
.type
!= SessionStartupPref::LAST
&&
725 !HasPendingUncleanExit(profile_
)) {
726 content::BrowserContext::GetDefaultStoragePartition(profile_
)->
727 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
733 Browser
* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
734 const std::vector
<GURL
>& urls_to_open
,
735 chrome::HostDesktopType desktop_type
) {
736 SessionStartupPref pref
=
737 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
739 // Pinned tabs should not be displayed when chrome is launched in incognito
740 // mode. Also, no pages should be opened automatically if the session
741 // crashed. Otherwise it might trigger another crash, locking the user out of
742 // chrome. The crash infobar is shown in this case.
743 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_
,
744 profile_
->GetPrefs()) &&
745 !HasPendingUncleanExit(profile_
)) {
746 tabs
= PinnedTabCodec::ReadPinnedTabs(profile_
);
749 RecordAppLaunches(profile_
, urls_to_open
, tabs
);
751 if (!urls_to_open
.empty()) {
752 // If urls were specified on the command line, use them.
753 UrlsToTabs(urls_to_open
, &tabs
);
754 } else if (pref
.type
== SessionStartupPref::DEFAULT
||
756 browser_creator_
&& !browser_creator_
->first_run_tabs_
.empty())) {
757 std::vector
<GURL
> urls
;
758 AddStartupURLs(&urls
);
759 UrlsToTabs(urls
, &tabs
);
760 } else if (pref
.type
== SessionStartupPref::URLS
&& !pref
.urls
.empty() &&
761 !HasPendingUncleanExit(profile_
)) {
762 // Only use the set of urls specified in preferences if nothing was
763 // specified on the command line. Filter out any urls that are to be
764 // restored by virtue of having been previously pinned.
765 AddUniqueURLs(pref
.urls
, &tabs
);
766 } else if (pref
.type
== SessionStartupPref::HOMEPAGE
) {
767 // If 'homepage' selected, either by the user or by a policy, we should
768 // have migrated them to another value.
769 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
775 Browser
* browser
= OpenTabsInBrowser(NULL
, true, tabs
, desktop_type
);
779 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector
<GURL
>& urls
,
781 size_t num_existing_tabs
= tabs
->size();
782 for (size_t i
= 0; i
< urls
.size(); ++i
) {
783 bool in_tabs
= false;
784 for (size_t j
= 0; j
< num_existing_tabs
; ++j
) {
785 if (urls
[i
] == (*tabs
)[j
].url
) {
792 tab
.is_pinned
= false;
794 tabs
->push_back(tab
);
799 Browser
* StartupBrowserCreatorImpl::OpenURLsInBrowser(
801 bool process_startup
,
802 const std::vector
<GURL
>& urls
,
803 chrome::HostDesktopType desktop_type
) {
805 UrlsToTabs(urls
, &tabs
);
806 return OpenTabsInBrowser(browser
, process_startup
, tabs
, desktop_type
);
809 Browser
* StartupBrowserCreatorImpl::OpenTabsInBrowser(
811 bool process_startup
,
812 const StartupTabs
& tabs
,
813 chrome::HostDesktopType desktop_type
) {
814 DCHECK(!tabs
.empty());
816 // If we don't yet have a profile, try to use the one we're given from
817 // |browser|. While we may not end up actually using |browser| (since it
818 // could be a popup window), we can at least use the profile.
819 if (!profile_
&& browser
)
820 profile_
= browser
->profile();
822 if (!browser
|| !browser
->is_type_tabbed()) {
823 browser
= new Browser(Browser::CreateParams(profile_
, desktop_type
));
825 #if defined(TOOLKIT_GTK)
826 // Setting the time of the last action on the window here allows us to steal
827 // focus, which is what the user wants when opening a new tab in an existing
829 gtk_util::SetWMLastUserActionTime(browser
->window()->GetNativeWindow());
833 // In kiosk mode, we want to always be fullscreen, so switch to that now.
834 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode
))
835 chrome::ToggleFullscreenMode(browser
);
837 bool first_tab
= true;
838 ProtocolHandlerRegistry
* registry
= profile_
?
839 ProtocolHandlerRegistryFactory::GetForProfile(profile_
) : NULL
;
840 for (size_t i
= 0; i
< tabs
.size(); ++i
) {
841 // We skip URLs that we'd have to launch an external protocol handler for.
842 // This avoids us getting into an infinite loop asking ourselves to open
843 // a URL, should the handler be (incorrectly) configured to be us. Anyone
844 // asking us to open such a URL should really ask the handler directly.
845 bool handled_by_chrome
= ProfileIOData::IsHandledURL(tabs
[i
].url
) ||
846 (registry
&& registry
->IsHandledProtocol(tabs
[i
].url
.scheme()));
847 if (!process_startup
&& !handled_by_chrome
)
850 int add_types
= first_tab
? TabStripModel::ADD_ACTIVE
:
851 TabStripModel::ADD_NONE
;
852 add_types
|= TabStripModel::ADD_FORCE_INDEX
;
853 if (tabs
[i
].is_pinned
)
854 add_types
|= TabStripModel::ADD_PINNED
;
856 chrome::NavigateParams
params(browser
, tabs
[i
].url
,
857 content::PAGE_TRANSITION_AUTO_TOPLEVEL
);
858 params
.disposition
= first_tab
? NEW_FOREGROUND_TAB
: NEW_BACKGROUND_TAB
;
859 params
.tabstrip_add_types
= add_types
;
860 params
.extension_app_id
= tabs
[i
].app_id
;
862 #if defined(ENABLE_RLZ)
863 if (process_startup
&& google_util::IsGoogleHomePageUrl(tabs
[i
].url
)) {
864 params
.extra_headers
= RLZTracker::GetAccessPointHttpHeader(
865 RLZTracker::CHROME_HOME_PAGE
);
869 chrome::Navigate(¶ms
);
873 if (!browser
->tab_strip_model()->GetActiveWebContents()) {
874 // TODO: this is a work around for 110909. Figure out why it's needed.
875 if (!browser
->tab_strip_model()->count())
876 chrome::AddTabAt(browser
, GURL(), -1, true);
878 browser
->tab_strip_model()->ActivateTabAt(0, false);
881 // The default behavior is to show the window, as expressed by the default
882 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
883 // to true ahead of this place, it means another task must have been spawned
884 // to take care of that.
885 if (!browser_creator_
|| browser_creator_
->show_main_browser_window())
886 browser
->window()->Show();
891 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
893 chrome::startup::IsProcessStartup is_process_startup
) {
894 if (!browser
|| !profile_
|| browser
->tab_strip_model()->count() == 0)
897 if (HasPendingUncleanExit(browser
->profile()))
898 SessionCrashedInfoBarDelegate::Create(browser
);
900 // The below info bars are only added to the first profile which is launched.
901 // Other profiles might be restoring the browsing sessions asynchronously,
902 // so we cannot add the info bars to the focused tabs here.
903 if (is_process_startup
== chrome::startup::IS_PROCESS_STARTUP
&&
904 !command_line_
.HasSwitch(switches::kTestType
)) {
905 chrome::ShowBadFlagsPrompt(browser
);
906 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
907 browser
->tab_strip_model()->GetActiveWebContents()));
908 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
909 browser
->tab_strip_model()->GetActiveWebContents()));
911 #if !defined(OS_CHROMEOS)
912 if (!command_line_
.HasSwitch(switches::kNoDefaultBrowserCheck
)) {
913 // Generally, the default browser prompt should not be shown on first
914 // run. However, when the set-as-default dialog has been suppressed, we
916 if ((!is_first_run_
||
918 browser_creator_
->is_default_browser_dialog_suppressed())) &&
919 !chrome::ShowAutolaunchPrompt(browser
)) {
920 chrome::ShowDefaultBrowserPrompt(profile_
,
921 browser
->host_desktop_type());
928 void StartupBrowserCreatorImpl::AddStartupURLs(
929 std::vector
<GURL
>* startup_urls
) const {
930 // TODO(atwilson): Simplify the logic that decides which tabs to open on
931 // start-up and make it more consistent. http://crbug.com/248883
933 // If we have urls specified by the first run master preferences use them
935 if (browser_creator_
&& startup_urls
->empty()) {
936 if (!browser_creator_
->first_run_tabs_
.empty()) {
937 std::vector
<GURL
>::iterator it
=
938 browser_creator_
->first_run_tabs_
.begin();
939 while (it
!= browser_creator_
->first_run_tabs_
.end()) {
940 // Replace magic names for the actual urls.
941 if (it
->host() == "new_tab_page") {
942 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
943 } else if (it
->host() == "welcome_page") {
944 startup_urls
->push_back(internals::GetWelcomePageURL());
946 startup_urls
->push_back(*it
);
950 browser_creator_
->first_run_tabs_
.clear();
954 // Otherwise open at least the new tab page (and the welcome page, if this
955 // is the first time the browser is being started), or the set of URLs
956 // specified on the command line.
957 if (startup_urls
->empty()) {
958 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
959 if (first_run::ShouldShowWelcomePage())
960 startup_urls
->push_back(internals::GetWelcomePageURL());
963 if (signin::ShouldShowPromoAtStartup(profile_
, is_first_run_
)) {
964 signin::DidShowPromoAtStartup(profile_
);
966 const GURL sync_promo_url
= signin::GetPromoURL(signin::SOURCE_START_PAGE
,
969 // No need to add if the sync promo is already in the startup list.
970 bool add_promo
= true;
971 for (std::vector
<GURL
>::const_iterator it
= startup_urls
->begin();
972 it
!= startup_urls
->end(); ++it
) {
973 if (*it
== sync_promo_url
) {
980 // If the first URL is the NTP, replace it with the sync promo. This
981 // behavior is desired because completing or skipping the sync promo
982 // causes a redirect to the NTP.
983 if (!startup_urls
->empty() && IsNewTabURL(profile_
, startup_urls
->at(0)))
984 startup_urls
->at(0) = sync_promo_url
;
986 startup_urls
->insert(startup_urls
->begin(), sync_promo_url
);
993 bool StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
995 const std::vector
<GURL
>& startup_urls
) {