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"
8 #include "base/bind_helpers.h"
9 #include "base/compiler_specific.h"
10 #include "base/environment.h"
11 #include "base/event_recorder.h"
12 #include "base/lazy_instance.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/statistics_recorder.h"
16 #include "base/path_service.h"
17 #include "base/string_number_conversions.h"
18 #include "base/string_split.h"
19 #include "base/threading/thread_restrictions.h"
20 #include "base/utf_string_conversions.h"
21 #include "chrome/browser/auto_launch_trial.h"
22 #include "chrome/browser/browser_process.h"
23 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
24 #include "chrome/browser/defaults.h"
25 #include "chrome/browser/extensions/extension_creator.h"
26 #include "chrome/browser/extensions/extension_service.h"
27 #include "chrome/browser/extensions/pack_extension_job.h"
28 #include "chrome/browser/first_run/first_run.h"
29 #include "chrome/browser/net/predictor.h"
30 #include "chrome/browser/net/url_fixer_upper.h"
31 #include "chrome/browser/notifications/desktop_notification_service.h"
32 #include "chrome/browser/prefs/incognito_mode_prefs.h"
33 #include "chrome/browser/prefs/pref_service.h"
34 #include "chrome/browser/prefs/session_startup_pref.h"
35 #include "chrome/browser/profiles/profile.h"
36 #include "chrome/browser/profiles/profile_io_data.h"
37 #include "chrome/browser/protector/protected_prefs_watcher.h"
38 #include "chrome/browser/protector/protector_service.h"
39 #include "chrome/browser/protector/protector_service_factory.h"
40 #include "chrome/browser/protector/protector_utils.h"
41 #include "chrome/browser/sessions/session_restore.h"
42 #include "chrome/browser/sessions/session_service.h"
43 #include "chrome/browser/sessions/session_service_factory.h"
44 #include "chrome/browser/shell_integration.h"
45 #include "chrome/browser/ui/browser_commands.h"
46 #include "chrome/browser/ui/browser_finder.h"
47 #include "chrome/browser/ui/browser_list.h"
48 #include "chrome/browser/ui/browser_navigator.h"
49 #include "chrome/browser/ui/browser_tabrestore.h"
50 #include "chrome/browser/ui/browser_tabstrip.h"
51 #include "chrome/browser/ui/browser_window.h"
52 #include "chrome/browser/ui/extensions/application_launch.h"
53 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
54 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
55 #include "chrome/browser/ui/startup/default_browser_prompt.h"
56 #include "chrome/browser/ui/startup/obsolete_os_prompt.h"
57 #include "chrome/browser/ui/startup/session_crashed_prompt.h"
58 #include "chrome/browser/ui/startup/startup_browser_creator.h"
59 #include "chrome/browser/ui/tab_contents/tab_contents.h"
60 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
61 #include "chrome/browser/ui/tabs/tab_strip_model.h"
62 #include "chrome/browser/ui/webui/ntp/app_launcher_handler.h"
63 #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h"
64 #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h"
65 #include "chrome/common/chrome_constants.h"
66 #include "chrome/common/chrome_notification_types.h"
67 #include "chrome/common/chrome_paths.h"
68 #include "chrome/common/chrome_result_codes.h"
69 #include "chrome/common/chrome_switches.h"
70 #include "chrome/common/chrome_version_info.h"
71 #include "chrome/common/extensions/extension_constants.h"
72 #include "chrome/common/pref_names.h"
73 #include "chrome/common/url_constants.h"
74 #include "chrome/installer/util/browser_distribution.h"
75 #include "content/public/browser/child_process_security_policy.h"
76 #include "content/public/browser/notification_observer.h"
77 #include "content/public/browser/notification_registrar.h"
78 #include "content/public/browser/web_contents.h"
79 #include "content/public/browser/web_contents_view.h"
80 #include "grit/locale_settings.h"
81 #include "ui/base/l10n/l10n_util.h"
82 #include "ui/base/resource/resource_bundle.h"
84 #if defined(OS_MACOSX)
85 #include "base/mac/mac_util.h"
86 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
89 #if defined(TOOLKIT_GTK)
90 #include "chrome/browser/ui/gtk/gtk_util.h"
94 #include "base/win/windows_version.h"
97 using content::ChildProcessSecurityPolicy
;
98 using content::WebContents
;
99 using extensions::Extension
;
100 using protector::ProtectedPrefsWatcher
;
101 using protector::ProtectorService
;
102 using protector::ProtectorServiceFactory
;
104 extern bool in_synchronous_profile_launch
;
108 // Utility functions ----------------------------------------------------------
111 LM_TO_BE_DECIDED
= 0, // Possibly direct launch or via a shortcut.
112 LM_AS_WEBAPP
, // Launched as a installed web application.
113 LM_WITH_URLS
, // Launched with urls in the cmd line.
114 LM_SHORTCUT_NONE
, // Not launched from a shortcut.
115 LM_SHORTCUT_NONAME
, // Launched from shortcut but no name available.
116 LM_SHORTCUT_UNKNOWN
, // Launched from user-defined shortcut.
117 LM_SHORTCUT_QUICKLAUNCH
, // Launched from the quick launch bar.
118 LM_SHORTCUT_DESKTOP
, // Launched from a desktop shortcut.
119 LM_SHORTCUT_TASKBAR
, // Launched from the taskbar.
120 LM_LINUX_MAC_BEOS
// Other OS buckets start here.
124 // Undocumented flag in the startup info structure tells us what shortcut was
125 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
126 // more information. Confirmed to work on XP, Vista and Win7.
127 LaunchMode
GetLaunchShortcutKind() {
128 STARTUPINFOW si
= { sizeof(si
) };
129 GetStartupInfoW(&si
);
130 if (si
.dwFlags
& 0x800) {
132 return LM_SHORTCUT_NONAME
;
133 string16
shortcut(si
.lpTitle
);
134 // The windows quick launch path is not localized.
135 if (shortcut
.find(L
"\\Quick Launch\\") != string16::npos
) {
136 if (base::win::GetVersion() >= base::win::VERSION_WIN7
)
137 return LM_SHORTCUT_TASKBAR
;
139 return LM_SHORTCUT_QUICKLAUNCH
;
141 scoped_ptr
<base::Environment
> env(base::Environment::Create());
142 std::string appdata_path
;
143 env
->GetVar("USERPROFILE", &appdata_path
);
144 if (!appdata_path
.empty() &&
145 shortcut
.find(ASCIIToWide(appdata_path
)) != std::wstring::npos
)
146 return LM_SHORTCUT_DESKTOP
;
147 return LM_SHORTCUT_UNKNOWN
;
149 return LM_SHORTCUT_NONE
;
152 // TODO(cpu): Port to other platforms.
153 LaunchMode
GetLaunchShortcutKind() {
154 return LM_LINUX_MAC_BEOS
;
158 // Log in a histogram the frequency of launching by the different methods. See
159 // LaunchMode enum for the actual values of the buckets.
160 void RecordLaunchModeHistogram(LaunchMode mode
) {
161 int bucket
= (mode
== LM_TO_BE_DECIDED
) ? GetLaunchShortcutKind() : mode
;
162 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket
);
165 GURL
GetWelcomePageURL() {
166 std::string welcome_url
= l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL
);
167 return GURL(welcome_url
);
170 void UrlsToTabs(const std::vector
<GURL
>& urls
, StartupTabs
* tabs
) {
171 for (size_t i
= 0; i
< urls
.size(); ++i
) {
173 tab
.is_pinned
= false;
175 tabs
->push_back(tab
);
179 // Return true if the command line option --app-id is used. Set
180 // |out_extension| to the app to open, and |out_launch_container|
181 // to the type of window into which the app should be open.
182 bool GetAppLaunchContainer(
184 const std::string
& app_id
,
185 const Extension
** out_extension
,
186 extension_misc::LaunchContainer
* out_launch_container
) {
188 ExtensionService
* extensions_service
= profile
->GetExtensionService();
189 const Extension
* extension
=
190 extensions_service
->GetExtensionById(app_id
, false);
192 // The extension with id |app_id| may have been uninstalled.
196 // Look at preferences to find the right launch container. If no
197 // preference is set, launch as a window.
198 extension_misc::LaunchContainer launch_container
=
199 extensions_service
->extension_prefs()->GetLaunchContainer(
200 extension
, extensions::ExtensionPrefs::LAUNCH_WINDOW
);
202 *out_extension
= extension
;
203 *out_launch_container
= launch_container
;
207 void RecordCmdLineAppHistogram() {
208 AppLauncherHandler::RecordAppLaunchType(
209 extension_misc::APP_LAUNCH_CMD_LINE_APP
);
212 void RecordAppLaunches(Profile
* profile
,
213 const std::vector
<GURL
>& cmd_line_urls
,
214 StartupTabs
& autolaunch_tabs
) {
215 ExtensionService
* extension_service
= profile
->GetExtensionService();
216 DCHECK(extension_service
);
217 for (size_t i
= 0; i
< cmd_line_urls
.size(); ++i
) {
218 if (extension_service
->IsInstalledApp(cmd_line_urls
.at(i
))) {
219 AppLauncherHandler::RecordAppLaunchType(
220 extension_misc::APP_LAUNCH_CMD_LINE_URL
);
223 for (size_t i
= 0; i
< autolaunch_tabs
.size(); ++i
) {
224 if (extension_service
->IsInstalledApp(autolaunch_tabs
.at(i
).url
)) {
225 AppLauncherHandler::RecordAppLaunchType(
226 extension_misc::APP_LAUNCH_AUTOLAUNCH
);
231 class WebContentsCloseObserver
: public content::NotificationObserver
{
233 WebContentsCloseObserver() : contents_(NULL
) {}
234 virtual ~WebContentsCloseObserver() {}
236 void SetContents(content::WebContents
* contents
) {
238 contents_
= contents
;
241 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
242 content::Source
<content::WebContents
>(contents_
));
245 content::WebContents
* contents() { return contents_
; }
248 // content::NotificationObserver overrides:
249 virtual void Observe(int type
,
250 const content::NotificationSource
& source
,
251 const content::NotificationDetails
& details
) OVERRIDE
{
252 DCHECK_EQ(type
, content::NOTIFICATION_WEB_CONTENTS_DESTROYED
);
256 content::WebContents
* contents_
;
257 content::NotificationRegistrar registrar_
;
259 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver
);
264 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
265 const FilePath
& cur_dir
,
266 const CommandLine
& command_line
,
267 chrome::startup::IsFirstRun is_first_run
)
269 command_line_(command_line
),
271 browser_creator_(NULL
),
272 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
275 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
276 const FilePath
& cur_dir
,
277 const CommandLine
& command_line
,
278 StartupBrowserCreator
* browser_creator
,
279 chrome::startup::IsFirstRun is_first_run
)
281 command_line_(command_line
),
283 browser_creator_(browser_creator
),
284 is_first_run_(is_first_run
== chrome::startup::IS_FIRST_RUN
) {
287 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
290 bool StartupBrowserCreatorImpl::Launch(Profile
* profile
,
291 const std::vector
<GURL
>& urls_to_open
,
292 bool process_startup
) {
296 if (command_line_
.HasSwitch(switches::kDnsLogDetails
))
297 chrome_browser_net::EnablePredictorDetailedLog(true);
298 if (command_line_
.HasSwitch(switches::kDnsPrefetchDisable
) &&
299 profile
->GetNetworkPredictor()) {
300 profile
->GetNetworkPredictor()->EnablePredictor(false);
303 if (command_line_
.HasSwitch(switches::kDumpHistogramsOnExit
))
304 base::StatisticsRecorder::set_dump_on_exit(true);
306 if (command_line_
.HasSwitch(switches::kRemoteDebuggingPort
)) {
307 std::string port_str
=
308 command_line_
.GetSwitchValueASCII(switches::kRemoteDebuggingPort
);
310 if (base::StringToInt64(port_str
, &port
) && port
> 0 && port
< 65535) {
311 std::string frontend_str
;
312 if (command_line_
.HasSwitch(switches::kRemoteDebuggingFrontend
)) {
313 frontend_str
= command_line_
.GetSwitchValueASCII(
314 switches::kRemoteDebuggingFrontend
);
316 g_browser_process
->InitDevToolsHttpProtocolHandler(
319 static_cast<int>(port
),
322 DLOG(WARNING
) << "Invalid http debugger port number " << port
;
326 // Open the required browser windows and tabs. First, see if
327 // we're being run as an application window. If so, the user
328 // opened an app shortcut. Don't restore tabs or open initial
329 // URLs in that case. The user should see the window as an app,
331 // Special case is when app switches are passed but we do want to restore
332 // session. In that case open app window + focus it after session is restored.
333 content::WebContents
* app_contents
= NULL
;
334 if (OpenApplicationWindow(profile
, &app_contents
) &&
335 !browser_defaults::kAppRestoreSession
) {
336 RecordLaunchModeHistogram(LM_AS_WEBAPP
);
338 RecordLaunchModeHistogram(urls_to_open
.empty() ?
339 LM_TO_BE_DECIDED
: LM_WITH_URLS
);
341 // Notify user if the Preferences backup is invalid or changes to settings
342 // affecting browser startup have been detected.
343 CheckPreferencesBackup(profile
);
345 // Watch for |app_contents| closing since ProcessLaunchURLs might run a
346 // synchronous session restore which has a nested message loop and could
347 // close |app_contents|.
348 WebContentsCloseObserver app_contents_observer
;
349 if (browser_defaults::kAppRestoreSession
&& app_contents
)
350 app_contents_observer
.SetContents(app_contents
);
352 ProcessLaunchURLs(process_startup
, urls_to_open
);
354 // If this is an app launch, but we didn't open an app window, it may
356 OpenApplicationTab(profile
);
358 // In case of app mode + session restore we want to focus that app.
359 if (app_contents_observer
.contents())
360 app_contents_observer
.contents()->GetView()->SetInitialFocus();
362 if (process_startup
) {
363 if (browser_defaults::kOSSupportsOtherBrowsers
&&
364 !command_line_
.HasSwitch(switches::kNoDefaultBrowserCheck
)) {
365 if (!chrome::ShowAutolaunchPrompt(profile
))
366 chrome::ShowDefaultBrowserPrompt(profile
);
368 #if defined(OS_MACOSX)
369 // Check whether the auto-update system needs to be promoted from user
371 KeystoneInfoBar::PromotionInfoBar(profile
);
376 // If we're recording or playing back, startup the EventRecorder now
377 // unless otherwise specified.
378 if (!command_line_
.HasSwitch(switches::kNoEvents
)) {
379 FilePath script_path
;
380 PathService::Get(chrome::FILE_RECORDED_SCRIPT
, &script_path
);
382 bool record_mode
= command_line_
.HasSwitch(switches::kRecordMode
);
383 bool playback_mode
= command_line_
.HasSwitch(switches::kPlaybackMode
);
385 if (record_mode
&& chrome::kRecordModeEnabled
)
386 base::EventRecorder::current()->StartRecording(script_path
);
387 // Do not enter Playback mode if PageCycler is running; Playback mode does
388 // not work correctly.
389 if (playback_mode
&& !command_line_
.HasSwitch(switches::kVisitURLs
))
390 base::EventRecorder::current()->StartPlayback(script_path
);
395 ShellIntegration::MigrateChromiumShortcuts();
396 #endif // defined(OS_WIN)
401 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string
* app_url
,
402 std::string
* app_id
) {
403 if (command_line_
.HasSwitch(switches::kApp
)) {
405 *app_url
= command_line_
.GetSwitchValueASCII(switches::kApp
);
408 if (command_line_
.HasSwitch(switches::kAppId
)) {
410 *app_id
= command_line_
.GetSwitchValueASCII(switches::kAppId
);
416 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile
* profile
) {
418 // App shortcuts to URLs always open in an app window. Because this
419 // function will open an app that should be in a tab, there is no need
420 // to look at the app URL. OpenApplicationWindow() will open app url
422 if (!IsAppLaunch(NULL
, &app_id
) || app_id
.empty())
425 extension_misc::LaunchContainer launch_container
;
426 const Extension
* extension
;
427 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
430 // If the user doesn't want to open a tab, fail.
431 if (launch_container
!= extension_misc::LAUNCH_TAB
)
434 RecordCmdLineAppHistogram();
436 WebContents
* app_tab
= application_launch::OpenApplication(
437 application_launch::LaunchParams(profile
, extension
,
438 extension_misc::LAUNCH_TAB
, NEW_FOREGROUND_TAB
));
439 return (app_tab
!= NULL
);
442 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
444 content::WebContents
** out_app_contents
) {
445 // Set |out_app_contents| to NULL early on (just in case).
446 if (out_app_contents
)
447 *out_app_contents
= NULL
;
449 std::string url_string
, app_id
;
450 if (!IsAppLaunch(&url_string
, &app_id
))
453 // This can fail if the app_id is invalid. It can also fail if the
454 // extension is external, and has not yet been installed.
455 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
456 // Open an URL to the gallery page of the extension id?
457 if (!app_id
.empty()) {
458 extension_misc::LaunchContainer launch_container
;
459 const Extension
* extension
;
460 if (!GetAppLaunchContainer(profile
, app_id
, &extension
, &launch_container
))
463 // TODO(skerner): Could pass in |extension| and |launch_container|,
464 // and avoid calling GetAppLaunchContainer() both here and in
465 // OpenApplicationTab().
467 if (launch_container
== extension_misc::LAUNCH_TAB
)
470 RecordCmdLineAppHistogram();
472 application_launch::LaunchParams
params(profile
, extension
,
473 launch_container
, NEW_WINDOW
);
474 params
.command_line
= &command_line_
;
475 WebContents
* tab_in_app_window
= application_launch::OpenApplication(
478 if (out_app_contents
)
479 *out_app_contents
= tab_in_app_window
;
481 // Platform apps fire off a launch event which may or may not open a window.
482 return (tab_in_app_window
!= NULL
|| extension
->is_platform_app());
485 if (url_string
.empty())
488 #if defined(OS_WIN) // Fix up Windows shortcuts.
489 ReplaceSubstringsAfterOffset(&url_string
, 0, "\\x", "%");
491 GURL
url(url_string
);
493 // Restrict allowed URLs for --app switch.
494 if (!url
.is_empty() && url
.is_valid()) {
495 ChildProcessSecurityPolicy
* policy
=
496 ChildProcessSecurityPolicy::GetInstance();
497 if (policy
->IsWebSafeScheme(url
.scheme()) ||
498 url
.SchemeIs(chrome::kFileScheme
)) {
499 if (profile
->GetExtensionService()->IsInstalledApp(url
)) {
500 RecordCmdLineAppHistogram();
502 AppLauncherHandler::RecordAppLaunchType(
503 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY
);
506 WebContents
* app_tab
= application_launch::OpenAppShortcutWindow(
510 if (out_app_contents
)
511 *out_app_contents
= app_tab
;
513 return (app_tab
!= NULL
);
519 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
520 bool process_startup
,
521 const std::vector
<GURL
>& urls_to_open
) {
522 // If we're starting up in "background mode" (no open browser window) then
523 // don't open any browser windows, unless kAutoLaunchAtStartup is also
525 if (process_startup
&&
526 command_line_
.HasSwitch(switches::kNoStartupWindow
) &&
527 !command_line_
.HasSwitch(switches::kAutoLaunchAtStartup
)) {
531 if (process_startup
&& ProcessStartupURLs(urls_to_open
)) {
532 // ProcessStartupURLs processed the urls, nothing else to do.
536 chrome::startup::IsProcessStartup is_process_startup
= process_startup
?
537 chrome::startup::IS_PROCESS_STARTUP
:
538 chrome::startup::IS_NOT_PROCESS_STARTUP
;
539 if (!process_startup
) {
540 // Even if we're not starting a new process, this may conceptually be
541 // "startup" for the user and so should be handled in a similar way. Eg.,
542 // Chrome may have been running in the background due to an app with a
543 // background page being installed, or running with only an app window
545 SessionService
* service
= SessionServiceFactory::GetForProfile(profile_
);
546 if (service
&& service
->ShouldNewWindowStartSession()) {
547 // Restore the last session if any.
548 if (!HasPendingUncleanExit(profile_
) &&
549 service
->RestoreIfNecessary(urls_to_open
)) {
552 // Open user-specified URLs like pinned tabs and startup tabs.
553 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
);
555 AddInfoBarsIfNecessary(browser
, is_process_startup
);
561 // Session startup didn't occur, open the urls.
563 Browser
* browser
= NULL
;
564 std::vector
<GURL
> adjust_urls
= urls_to_open
;
565 if (adjust_urls
.empty())
566 AddStartupURLs(&adjust_urls
);
567 else if (!command_line_
.HasSwitch(switches::kOpenInNewWindow
))
568 browser
= browser::FindLastActiveWithProfile(profile_
);
570 // This will launch a browser; prevent session restore.
571 in_synchronous_profile_launch
= true;
572 browser
= OpenURLsInBrowser(browser
, process_startup
, adjust_urls
);
573 in_synchronous_profile_launch
= false;
574 AddInfoBarsIfNecessary(browser
, is_process_startup
);
577 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
578 const std::vector
<GURL
>& urls_to_open
) {
579 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
580 SessionStartupPref pref
=
581 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
582 if (pref
.type
== SessionStartupPref::LAST
)
583 VLOG(1) << "Pref: last";
584 else if (pref
.type
== SessionStartupPref::URLS
)
585 VLOG(1) << "Pref: urls";
586 else if (pref
.type
== SessionStartupPref::DEFAULT
)
587 VLOG(1) << "Pref: default";
589 if (pref
.type
== SessionStartupPref::LAST
) {
590 if (!profile_
->DidLastSessionExitCleanly() &&
591 !command_line_
.HasSwitch(switches::kRestoreLastSession
)) {
592 // The last session crashed. It's possible automatically loading the
593 // page will trigger another crash, locking the user out of chrome.
594 // To avoid this, don't restore on startup but instead show the crashed
596 VLOG(1) << "Unclean exit; not processing";
600 uint32 restore_behavior
= SessionRestore::SYNCHRONOUS
|
601 SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
602 #if defined(OS_MACOSX)
603 // On Mac, when restoring a session with no windows, suppress the creation
604 // of a new window in the case where the system is launching Chrome via a
605 // login item or Lion's resume feature.
606 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
607 restore_behavior
= restore_behavior
&
608 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER
;
612 Browser
* browser
= SessionRestore::RestoreSession(profile_
,
616 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
620 Browser
* browser
= ProcessSpecifiedURLs(urls_to_open
);
624 AddInfoBarsIfNecessary(browser
, chrome::startup::IS_PROCESS_STARTUP
);
628 Browser
* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
629 const std::vector
<GURL
>& urls_to_open
) {
630 SessionStartupPref pref
=
631 StartupBrowserCreator::GetSessionStartupPref(command_line_
, profile_
);
633 // Pinned tabs should not be displayed when chrome is launched in incognito
634 // mode. Also, no pages should be opened automatically if the session
635 // crashed. Otherwise it might trigger another crash, locking the user out of
636 // chrome. The crash infobar is shown in this case.
637 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_
,
638 profile_
->GetPrefs()) &&
639 !HasPendingUncleanExit(profile_
)) {
640 tabs
= PinnedTabCodec::ReadPinnedTabs(profile_
);
643 RecordAppLaunches(profile_
, urls_to_open
, tabs
);
645 if (!urls_to_open
.empty()) {
646 // If urls were specified on the command line, use them.
647 UrlsToTabs(urls_to_open
, &tabs
);
648 } else if (pref
.type
== SessionStartupPref::DEFAULT
||
650 browser_creator_
&& !browser_creator_
->first_run_tabs_
.empty())) {
651 std::vector
<GURL
> urls
;
652 AddStartupURLs(&urls
);
653 UrlsToTabs(urls
, &tabs
);
654 } else if (pref
.type
== SessionStartupPref::URLS
&& !pref
.urls
.empty() &&
655 !HasPendingUncleanExit(profile_
)) {
656 // Only use the set of urls specified in preferences if nothing was
657 // specified on the command line. Filter out any urls that are to be
658 // restored by virtue of having been previously pinned.
659 AddUniqueURLs(pref
.urls
, &tabs
);
660 } else if (pref
.type
== SessionStartupPref::HOMEPAGE
) {
661 // If 'homepage' selected, either by the user or by a policy, we should
662 // have migrated them to another value.
663 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
669 Browser
* browser
= OpenTabsInBrowser(NULL
, true, tabs
);
673 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector
<GURL
>& urls
,
675 size_t num_existing_tabs
= tabs
->size();
676 for (size_t i
= 0; i
< urls
.size(); ++i
) {
677 bool in_tabs
= false;
678 for (size_t j
= 0; j
< num_existing_tabs
; ++j
) {
679 if (urls
[i
] == (*tabs
)[j
].url
) {
686 tab
.is_pinned
= false;
688 tabs
->push_back(tab
);
693 Browser
* StartupBrowserCreatorImpl::OpenURLsInBrowser(
695 bool process_startup
,
696 const std::vector
<GURL
>& urls
) {
698 UrlsToTabs(urls
, &tabs
);
699 return OpenTabsInBrowser(browser
, process_startup
, tabs
);
702 Browser
* StartupBrowserCreatorImpl::OpenTabsInBrowser(Browser
* browser
,
703 bool process_startup
,
704 const StartupTabs
& tabs
) {
705 DCHECK(!tabs
.empty());
707 // If we don't yet have a profile, try to use the one we're given from
708 // |browser|. While we may not end up actually using |browser| (since it
709 // could be a popup window), we can at least use the profile.
710 if (!profile_
&& browser
)
711 profile_
= browser
->profile();
713 if (!browser
|| !browser
->is_type_tabbed()) {
714 browser
= Browser::Create(profile_
);
716 #if defined(TOOLKIT_GTK)
717 // Setting the time of the last action on the window here allows us to steal
718 // focus, which is what the user wants when opening a new tab in an existing
720 gtk_util::SetWMLastUserActionTime(browser
->window()->GetNativeWindow());
724 // In kiosk mode, we want to always be fullscreen, so switch to that now.
725 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode
))
726 chrome::ToggleFullscreenMode(browser
);
728 bool first_tab
= true;
729 for (size_t i
= 0; i
< tabs
.size(); ++i
) {
730 // We skip URLs that we'd have to launch an external protocol handler for.
731 // This avoids us getting into an infinite loop asking ourselves to open
732 // a URL, should the handler be (incorrectly) configured to be us. Anyone
733 // asking us to open such a URL should really ask the handler directly.
734 bool handled_by_chrome
= ProfileIOData::IsHandledURL(tabs
[i
].url
) ||
735 (profile_
&& profile_
->GetProtocolHandlerRegistry()->IsHandledProtocol(
736 tabs
[i
].url
.scheme()));
737 if (!process_startup
&& !handled_by_chrome
)
740 int add_types
= first_tab
? TabStripModel::ADD_ACTIVE
:
741 TabStripModel::ADD_NONE
;
742 add_types
|= TabStripModel::ADD_FORCE_INDEX
;
743 if (tabs
[i
].is_pinned
)
744 add_types
|= TabStripModel::ADD_PINNED
;
745 int index
= chrome::GetIndexForInsertionDuringRestore(browser
, i
);
747 chrome::NavigateParams
params(browser
, tabs
[i
].url
,
748 content::PAGE_TRANSITION_START_PAGE
);
749 params
.disposition
= first_tab
? NEW_FOREGROUND_TAB
: NEW_BACKGROUND_TAB
;
750 params
.tabstrip_index
= index
;
751 params
.tabstrip_add_types
= add_types
;
752 params
.extension_app_id
= tabs
[i
].app_id
;
753 chrome::Navigate(¶ms
);
757 if (!chrome::GetActiveWebContents(browser
)) {
758 // TODO: this is a work around for 110909. Figure out why it's needed.
759 if (!browser
->tab_count())
760 chrome::AddBlankTab(browser
, true);
762 chrome::ActivateTabAt(browser
, 0, false);
765 browser
->window()->Show();
766 // TODO(jcampan): http://crbug.com/8123 we should not need to set the initial
768 chrome::GetActiveWebContents(browser
)->GetView()->SetInitialFocus();
773 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
775 chrome::startup::IsProcessStartup is_process_startup
) {
776 if (!browser
|| !profile_
|| browser
->tab_count() == 0)
779 if (HasPendingUncleanExit(browser
->profile()))
780 chrome::ShowSessionCrashedPrompt(browser
);
782 // The bad flags info bar and the obsolete system info bar are only added to
783 // the first profile which is launched. Other profiles might be restoring the
784 // browsing sessions asynchronously, so we cannot add the info bars to the
785 // focused tabs here.
786 if (is_process_startup
== chrome::startup::IS_PROCESS_STARTUP
) {
787 chrome::ShowBadFlagsPrompt(browser
);
788 chrome::ShowObsoleteOSPrompt(browser
);
793 void StartupBrowserCreatorImpl::AddStartupURLs(
794 std::vector
<GURL
>* startup_urls
) const {
795 // If we have urls specified by the first run master preferences use them
797 if (browser_creator_
&& startup_urls
->empty()) {
798 if (!browser_creator_
->first_run_tabs_
.empty()) {
799 std::vector
<GURL
>::iterator it
=
800 browser_creator_
->first_run_tabs_
.begin();
801 while (it
!= browser_creator_
->first_run_tabs_
.end()) {
802 // Replace magic names for the actual urls.
803 if (it
->host() == "new_tab_page") {
804 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
805 } else if (it
->host() == "welcome_page") {
806 startup_urls
->push_back(GetWelcomePageURL());
808 startup_urls
->push_back(*it
);
812 browser_creator_
->first_run_tabs_
.clear();
816 // Otherwise open at least the new tab page (and the welcome page, if this
817 // is the first time the browser is being started), or the set of URLs
818 // specified on the command line.
819 if (startup_urls
->empty()) {
820 startup_urls
->push_back(GURL(chrome::kChromeUINewTabURL
));
821 PrefService
* prefs
= g_browser_process
->local_state();
822 if (prefs
->FindPreference(prefs::kShouldShowWelcomePage
) &&
823 prefs
->GetBoolean(prefs::kShouldShowWelcomePage
)) {
824 // Reset the preference so we don't show the welcome page next time.
825 prefs
->ClearPref(prefs::kShouldShowWelcomePage
);
826 startup_urls
->push_back(GetWelcomePageURL());
830 // If the sync promo page is going to be displayed then insert it at the front
832 if (SyncPromoUI::ShouldShowSyncPromoAtStartup(profile_
, is_first_run_
)) {
833 SyncPromoUI::DidShowSyncPromoAtStartup(profile_
);
834 GURL old_url
= (*startup_urls
)[0];
836 SyncPromoUI::GetSyncPromoURL(GURL(chrome::kChromeUINewTabURL
),
837 SyncPromoUI::SOURCE_START_PAGE
);
839 // An empty URL means to go to the home page.
840 if (old_url
.is_empty() &&
841 profile_
->GetHomePage() == GURL(chrome::kChromeUINewTabURL
)) {
842 old_url
= GURL(chrome::kChromeUINewTabURL
);
845 // If the old URL is not the NTP then insert it right after the sync promo.
846 if (old_url
!= GURL(chrome::kChromeUINewTabURL
))
847 startup_urls
->insert(startup_urls
->begin() + 1, old_url
);
849 // If we have more than two startup tabs then skip the welcome page.
850 if (startup_urls
->size() > 2) {
851 std::vector
<GURL
>::iterator it
= std::find(
852 startup_urls
->begin(), startup_urls
->end(), GetWelcomePageURL());
853 if (it
!= startup_urls
->end())
854 startup_urls
->erase(it
);
859 void StartupBrowserCreatorImpl::CheckPreferencesBackup(Profile
* profile
) {
860 ProtectorService
* protector_service
=
861 ProtectorServiceFactory::GetForProfile(profile
);
862 ProtectedPrefsWatcher
* prefs_watcher
= protector_service
->GetPrefsWatcher();
864 // Check if backup is valid.
865 if (!prefs_watcher
->is_backup_valid()) {
866 protector_service
->ShowChange(protector::CreatePrefsBackupInvalidChange());
867 // Further checks make no sense.
871 // Check for session startup (including pinned tabs) changes.
872 if (SessionStartupPref::DidStartupPrefChange(profile
) ||
873 prefs_watcher
->DidPrefChange(prefs::kPinnedTabs
)) {
874 LOG(WARNING
) << "Session startup settings have changed";
875 SessionStartupPref new_pref
= SessionStartupPref::GetStartupPref(profile
);
876 StartupTabs new_tabs
= PinnedTabCodec::ReadPinnedTabs(profile
);
877 const base::Value
* tabs_backup
=
878 prefs_watcher
->GetBackupForPref(prefs::kPinnedTabs
);
879 protector_service
->ShowChange(protector::CreateSessionStartupChange(
882 SessionStartupPref::GetStartupPrefBackup(profile
),
883 PinnedTabCodec::ReadPinnedTabs(tabs_backup
)));
886 // Check for homepage changes.
887 if (prefs_watcher
->DidPrefChange(prefs::kHomePage
) ||
888 prefs_watcher
->DidPrefChange(prefs::kHomePageIsNewTabPage
) ||
889 prefs_watcher
->DidPrefChange(prefs::kShowHomeButton
)) {
890 LOG(WARNING
) << "Homepage has changed";
891 PrefService
* prefs
= profile
->GetPrefs();
892 std::string backup_homepage
;
893 bool backup_homepage_is_ntp
;
894 bool backup_show_home_button
;
895 if (!prefs_watcher
->GetBackupForPref(prefs::kHomePage
)->
896 GetAsString(&backup_homepage
) ||
897 !prefs_watcher
->GetBackupForPref(prefs::kHomePageIsNewTabPage
)->
898 GetAsBoolean(&backup_homepage_is_ntp
) ||
899 !prefs_watcher
->GetBackupForPref(prefs::kShowHomeButton
)->
900 GetAsBoolean(&backup_show_home_button
)) {
903 protector_service
->ShowChange(protector::CreateHomepageChange(
905 prefs
->GetString(prefs::kHomePage
),
906 prefs
->GetBoolean(prefs::kHomePageIsNewTabPage
),
907 prefs
->GetBoolean(prefs::kShowHomeButton
),
910 backup_homepage_is_ntp
,
911 backup_show_home_button
));