Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / ui / startup / startup_browser_creator_impl.cc
blob2caa700560b51b257cea21f8e4b5c9b4adb350ef
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"
7 #include <algorithm>
8 #include <vector>
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/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_service.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_bubble.h"
70 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
71 #include "chrome/browser/ui/startup/startup_browser_creator.h"
72 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
73 #include "chrome/browser/ui/tabs/tab_strip_model.h"
74 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
75 #include "chrome/common/chrome_constants.h"
76 #include "chrome/common/chrome_paths.h"
77 #include "chrome/common/chrome_result_codes.h"
78 #include "chrome/common/chrome_switches.h"
79 #include "chrome/common/chrome_version_info.h"
80 #include "chrome/common/extensions/extension_constants.h"
81 #include "chrome/common/net/url_fixer_upper.h"
82 #include "chrome/common/pref_names.h"
83 #include "chrome/common/url_constants.h"
84 #include "chrome/installer/util/browser_distribution.h"
85 #include "content/public/browser/child_process_security_policy.h"
86 #include "content/public/browser/dom_storage_context.h"
87 #include "content/public/browser/notification_observer.h"
88 #include "content/public/browser/notification_registrar.h"
89 #include "content/public/browser/storage_partition.h"
90 #include "content/public/browser/web_contents.h"
91 #include "extensions/browser/extension_prefs.h"
92 #include "extensions/browser/extension_registry.h"
93 #include "extensions/browser/extension_system.h"
94 #include "extensions/common/constants.h"
95 #include "extensions/common/extension.h"
96 #include "extensions/common/extension_set.h"
97 #include "grit/locale_settings.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/base/resource/resource_bundle.h"
101 #if defined(OS_MACOSX)
102 #include "base/mac/mac_util.h"
103 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
104 #endif
106 #if defined(OS_WIN)
107 #include "base/win/windows_version.h"
108 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
109 #endif
111 using content::ChildProcessSecurityPolicy;
112 using content::WebContents;
113 using extensions::Extension;
115 namespace {
117 // Utility functions ----------------------------------------------------------
119 enum LaunchMode {
120 LM_TO_BE_DECIDED = 0, // Possibly direct launch or via a shortcut.
121 LM_AS_WEBAPP, // Launched as a installed web application.
122 LM_WITH_URLS, // Launched with urls in the cmd line.
123 LM_SHORTCUT_NONE, // Not launched from a shortcut.
124 LM_SHORTCUT_NONAME, // Launched from shortcut but no name available.
125 LM_SHORTCUT_UNKNOWN, // Launched from user-defined shortcut.
126 LM_SHORTCUT_QUICKLAUNCH, // Launched from the quick launch bar.
127 LM_SHORTCUT_DESKTOP, // Launched from a desktop shortcut.
128 LM_SHORTCUT_TASKBAR, // Launched from the taskbar.
129 LM_LINUX_MAC_BEOS // Other OS buckets start here.
132 #if defined(OS_WIN)
133 // Undocumented flag in the startup info structure tells us what shortcut was
134 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
135 // more information. Confirmed to work on XP, Vista and Win7.
136 LaunchMode GetLaunchShortcutKind() {
137 STARTUPINFOW si = { sizeof(si) };
138 GetStartupInfoW(&si);
139 if (si.dwFlags & 0x800) {
140 if (!si.lpTitle)
141 return LM_SHORTCUT_NONAME;
142 base::string16 shortcut(si.lpTitle);
143 // The windows quick launch path is not localized.
144 if (shortcut.find(L"\\Quick Launch\\") != base::string16::npos) {
145 if (base::win::GetVersion() >= base::win::VERSION_WIN7)
146 return LM_SHORTCUT_TASKBAR;
147 else
148 return LM_SHORTCUT_QUICKLAUNCH;
150 scoped_ptr<base::Environment> env(base::Environment::Create());
151 std::string appdata_path;
152 env->GetVar("USERPROFILE", &appdata_path);
153 if (!appdata_path.empty() &&
154 shortcut.find(base::ASCIIToWide(appdata_path)) != std::wstring::npos)
155 return LM_SHORTCUT_DESKTOP;
156 return LM_SHORTCUT_UNKNOWN;
158 return LM_SHORTCUT_NONE;
160 #else
161 // TODO(cpu): Port to other platforms.
162 LaunchMode GetLaunchShortcutKind() {
163 return LM_LINUX_MAC_BEOS;
165 #endif
167 // Log in a histogram the frequency of launching by the different methods. See
168 // LaunchMode enum for the actual values of the buckets.
169 void RecordLaunchModeHistogram(LaunchMode mode) {
170 int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
171 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
174 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
175 for (size_t i = 0; i < urls.size(); ++i) {
176 StartupTab tab;
177 tab.is_pinned = false;
178 tab.url = urls[i];
179 tabs->push_back(tab);
183 // Return true if the command line option --app-id is used. Set
184 // |out_extension| to the app to open, and |out_launch_container|
185 // to the type of window into which the app should be open.
186 bool GetAppLaunchContainer(
187 Profile* profile,
188 const std::string& app_id,
189 const Extension** out_extension,
190 extensions::LaunchContainer* out_launch_container) {
192 ExtensionService* extensions_service = profile->GetExtensionService();
193 const Extension* extension =
194 extensions_service->GetExtensionById(app_id, false);
195 // The extension with id |app_id| may have been uninstalled.
196 if (!extension)
197 return false;
199 // Don't launch platform apps in incognito mode.
200 if (profile->IsOffTheRecord() && extension->is_platform_app())
201 return false;
203 // Look at preferences to find the right launch container. If no
204 // preference is set, launch as a window.
205 extensions::LaunchContainer launch_container = extensions::GetLaunchContainer(
206 extensions::ExtensionPrefs::Get(profile), extension);
208 if (!CommandLine::ForCurrentProcess()->HasSwitch(
209 switches::kEnableStreamlinedHostedApps) &&
210 !extensions::HasPreferredLaunchContainer(
211 extensions::ExtensionPrefs::Get(profile), extension)) {
212 launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
215 *out_extension = extension;
216 *out_launch_container = launch_container;
217 return true;
220 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
221 CoreAppLauncherHandler::RecordAppLaunchType(
222 extension_misc::APP_LAUNCH_CMD_LINE_APP,
223 app_type);
226 void RecordAppLaunches(Profile* profile,
227 const std::vector<GURL>& cmd_line_urls,
228 StartupTabs& autolaunch_tabs) {
229 const extensions::ExtensionSet& extensions =
230 extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
231 for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
232 const extensions::Extension* extension =
233 extensions.GetAppByURL(cmd_line_urls.at(i));
234 if (extension) {
235 CoreAppLauncherHandler::RecordAppLaunchType(
236 extension_misc::APP_LAUNCH_CMD_LINE_URL,
237 extension->GetType());
240 for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
241 const extensions::Extension* extension =
242 extensions.GetAppByURL(autolaunch_tabs.at(i).url);
243 if (extension) {
244 CoreAppLauncherHandler::RecordAppLaunchType(
245 extension_misc::APP_LAUNCH_AUTOLAUNCH,
246 extension->GetType());
251 bool IsNewTabURL(Profile* profile, const GURL& url) {
252 GURL ntp_url(chrome::kChromeUINewTabURL);
253 return url == ntp_url ||
254 (url.is_empty() && profile->GetHomePage() == ntp_url);
257 class WebContentsCloseObserver : public content::NotificationObserver {
258 public:
259 WebContentsCloseObserver() : contents_(NULL) {}
260 virtual ~WebContentsCloseObserver() {}
262 void SetContents(content::WebContents* contents) {
263 DCHECK(!contents_);
264 contents_ = contents;
266 registrar_.Add(this,
267 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
268 content::Source<content::WebContents>(contents_));
271 content::WebContents* contents() { return contents_; }
273 private:
274 // content::NotificationObserver overrides:
275 virtual void Observe(int type,
276 const content::NotificationSource& source,
277 const content::NotificationDetails& details) OVERRIDE {
278 DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
279 contents_ = NULL;
282 content::WebContents* contents_;
283 content::NotificationRegistrar registrar_;
285 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
288 // TODO(koz): Consolidate this function and remove the special casing.
289 const Extension* GetPlatformApp(Profile* profile,
290 const std::string& extension_id) {
291 const Extension* extension =
292 extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
293 extension_id, extensions::ExtensionRegistry::EVERYTHING);
294 return extension && extension->is_platform_app() ? extension : NULL;
297 } // namespace
299 namespace internals {
301 GURL GetWelcomePageURL() {
302 std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
303 return GURL(welcome_url);
306 } // namespace internals
308 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
309 const base::FilePath& cur_dir,
310 const CommandLine& command_line,
311 chrome::startup::IsFirstRun is_first_run)
312 : cur_dir_(cur_dir),
313 command_line_(command_line),
314 profile_(NULL),
315 browser_creator_(NULL),
316 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
319 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
320 const base::FilePath& cur_dir,
321 const CommandLine& command_line,
322 StartupBrowserCreator* browser_creator,
323 chrome::startup::IsFirstRun is_first_run)
324 : cur_dir_(cur_dir),
325 command_line_(command_line),
326 profile_(NULL),
327 browser_creator_(browser_creator),
328 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
331 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
334 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
335 const std::vector<GURL>& urls_to_open,
336 bool process_startup,
337 chrome::HostDesktopType desktop_type) {
338 DCHECK(profile);
339 profile_ = profile;
341 if (command_line_.HasSwitch(switches::kDnsLogDetails))
342 chrome_browser_net::EnablePredictorDetailedLog(true);
343 if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
344 profile->GetNetworkPredictor()) {
345 profile->GetNetworkPredictor()->EnablePredictor(false);
348 AppListService::InitAll(profile);
349 if (command_line_.HasSwitch(switches::kAppId)) {
350 std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
351 const Extension* extension = GetPlatformApp(profile, app_id);
352 // If |app_id| is a disabled or terminated platform app we handle it
353 // specially here, otherwise it will be handled below.
354 if (extension) {
355 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
356 AppLaunchParams params(profile, extension,
357 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW);
358 params.command_line = command_line_;
359 params.current_directory = cur_dir_;
360 // If we are being launched from the command line, default to native
361 // desktop.
362 params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
363 OpenApplicationWithReenablePrompt(params);
364 return true;
366 } else if (command_line_.HasSwitch(switches::kShowAppList)) {
367 // This switch is used for shortcuts on the native desktop.
368 AppListService::RecordShowTimings(command_line_);
369 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
370 ShowForProfile(profile);
371 return true;
374 // Open the required browser windows and tabs. First, see if
375 // we're being run as an application window. If so, the user
376 // opened an app shortcut. Don't restore tabs or open initial
377 // URLs in that case. The user should see the window as an app,
378 // not as chrome.
379 // Special case is when app switches are passed but we do want to restore
380 // session. In that case open app window + focus it after session is restored.
381 content::WebContents* app_contents = NULL;
382 if (OpenApplicationWindow(profile, &app_contents)) {
383 RecordLaunchModeHistogram(LM_AS_WEBAPP);
384 } else {
385 RecordLaunchModeHistogram(urls_to_open.empty() ?
386 LM_TO_BE_DECIDED : LM_WITH_URLS);
388 ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
390 if (command_line_.HasSwitch(switches::kInstallChromeApp)) {
391 install_chrome_app::InstallChromeApp(
392 command_line_.GetSwitchValueASCII(switches::kInstallChromeApp));
395 // If this is an app launch, but we didn't open an app window, it may
396 // be an app tab.
397 OpenApplicationTab(profile);
399 #if defined(OS_MACOSX)
400 if (process_startup) {
401 // Check whether the auto-update system needs to be promoted from user
402 // to system.
403 KeystoneInfoBar::PromotionInfoBar(profile);
405 #endif
408 #if defined(OS_WIN)
409 if (process_startup)
410 ShellIntegration::MigrateChromiumShortcuts();
411 #endif // defined(OS_WIN)
413 return true;
416 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
417 std::string* app_id) {
418 if (command_line_.HasSwitch(switches::kApp)) {
419 if (app_url)
420 *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
421 return true;
423 if (command_line_.HasSwitch(switches::kAppId)) {
424 if (app_id)
425 *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
426 return true;
428 return false;
431 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
432 std::string app_id;
433 // App shortcuts to URLs always open in an app window. Because this
434 // function will open an app that should be in a tab, there is no need
435 // to look at the app URL. OpenApplicationWindow() will open app url
436 // shortcuts.
437 if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
438 return false;
440 extensions::LaunchContainer launch_container;
441 const Extension* extension;
442 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
443 return false;
445 // If the user doesn't want to open a tab, fail.
446 if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
447 return false;
449 RecordCmdLineAppHistogram(extension->GetType());
451 WebContents* app_tab = OpenApplication(AppLaunchParams(
452 profile, extension, extensions::LAUNCH_CONTAINER_TAB,
453 NEW_FOREGROUND_TAB));
454 return (app_tab != NULL);
457 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
458 Profile* profile,
459 content::WebContents** out_app_contents) {
460 // Set |out_app_contents| to NULL early on (just in case).
461 if (out_app_contents)
462 *out_app_contents = NULL;
464 std::string url_string, app_id;
465 if (!IsAppLaunch(&url_string, &app_id))
466 return false;
468 // This can fail if the app_id is invalid. It can also fail if the
469 // extension is external, and has not yet been installed.
470 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
471 // Open an URL to the gallery page of the extension id?
472 if (!app_id.empty()) {
473 extensions::LaunchContainer launch_container;
474 const Extension* extension;
475 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
476 return false;
478 // TODO(skerner): Could pass in |extension| and |launch_container|,
479 // and avoid calling GetAppLaunchContainer() both here and in
480 // OpenApplicationTab().
482 if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
483 return false;
485 RecordCmdLineAppHistogram(extension->GetType());
487 AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW);
488 params.command_line = command_line_;
489 params.current_directory = cur_dir_;
490 WebContents* tab_in_app_window = OpenApplication(params);
492 if (out_app_contents)
493 *out_app_contents = tab_in_app_window;
495 // Platform apps fire off a launch event which may or may not open a window.
496 return (tab_in_app_window != NULL || extension->is_platform_app());
499 if (url_string.empty())
500 return false;
502 #if defined(OS_WIN) // Fix up Windows shortcuts.
503 ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
504 #endif
505 GURL url(url_string);
507 // Restrict allowed URLs for --app switch.
508 if (!url.is_empty() && url.is_valid()) {
509 ChildProcessSecurityPolicy* policy =
510 ChildProcessSecurityPolicy::GetInstance();
511 if (policy->IsWebSafeScheme(url.scheme()) ||
512 url.SchemeIs(content::kFileScheme)) {
513 const extensions::Extension* extension =
514 extensions::ExtensionRegistry::Get(profile)
515 ->enabled_extensions().GetAppByURL(url);
516 if (extension) {
517 RecordCmdLineAppHistogram(extension->GetType());
518 } else {
519 CoreAppLauncherHandler::RecordAppLaunchType(
520 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
521 extensions::Manifest::TYPE_HOSTED_APP);
524 WebContents* app_tab = OpenAppShortcutWindow(profile, url);
526 if (out_app_contents)
527 *out_app_contents = app_tab;
529 return (app_tab != NULL);
532 return false;
535 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
536 bool process_startup,
537 const std::vector<GURL>& urls_to_open,
538 chrome::HostDesktopType desktop_type) {
539 // If we're starting up in "background mode" (no open browser window) then
540 // don't open any browser windows, unless kAutoLaunchAtStartup is also
541 // specified.
542 if (process_startup &&
543 command_line_.HasSwitch(switches::kNoStartupWindow) &&
544 !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
545 return;
548 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
549 #if defined(OS_WIN)
550 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
551 // See if there are apps for this profile that should be launched on startup
552 // due to a switch from Metro mode.
553 app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
555 #endif
557 if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
558 // ProcessStartupURLs processed the urls, nothing else to do.
559 return;
562 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
563 chrome::startup::IS_PROCESS_STARTUP :
564 chrome::startup::IS_NOT_PROCESS_STARTUP;
565 if (!process_startup) {
566 // Even if we're not starting a new process, this may conceptually be
567 // "startup" for the user and so should be handled in a similar way. Eg.,
568 // Chrome may have been running in the background due to an app with a
569 // background page being installed, or running with only an app window
570 // displayed.
571 SessionService* service =
572 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
573 if (service && service->ShouldNewWindowStartSession()) {
574 // Restore the last session if any.
575 if (!HasPendingUncleanExit(profile_) &&
576 service->RestoreIfNecessary(urls_to_open)) {
577 return;
579 // Open user-specified URLs like pinned tabs and startup tabs.
580 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
581 if (browser) {
582 AddInfoBarsIfNecessary(browser, is_process_startup);
583 return;
588 // Session startup didn't occur, open the urls.
589 Browser* browser = NULL;
590 std::vector<GURL> adjust_urls = urls_to_open;
591 if (adjust_urls.empty()) {
592 AddStartupURLs(&adjust_urls);
593 } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
594 // Always open a list of urls in a window on the native desktop.
595 browser = chrome::FindTabbedBrowser(profile_, false,
596 chrome::HOST_DESKTOP_TYPE_NATIVE);
598 // This will launch a browser; prevent session restore.
599 StartupBrowserCreator::in_synchronous_profile_launch_ = true;
600 browser = OpenURLsInBrowser(browser, process_startup, adjust_urls,
601 desktop_type);
602 StartupBrowserCreator::in_synchronous_profile_launch_ = false;
603 AddInfoBarsIfNecessary(browser, is_process_startup);
606 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
607 const std::vector<GURL>& urls_to_open,
608 chrome::HostDesktopType desktop_type) {
609 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
610 SessionStartupPref pref =
611 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
612 if (pref.type == SessionStartupPref::LAST)
613 VLOG(1) << "Pref: last";
614 else if (pref.type == SessionStartupPref::URLS)
615 VLOG(1) << "Pref: urls";
616 else if (pref.type == SessionStartupPref::DEFAULT)
617 VLOG(1) << "Pref: default";
619 apps::AppRestoreService* restore_service =
620 apps::AppRestoreServiceFactory::GetForProfile(profile_);
621 // NULL in incognito mode.
622 if (restore_service) {
623 restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
624 StartupBrowserCreator::WasRestarted()));
627 if (pref.type == SessionStartupPref::LAST) {
628 if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
629 !command_line_.HasSwitch(switches::kRestoreLastSession)) {
630 // The last session crashed. It's possible automatically loading the
631 // page will trigger another crash, locking the user out of chrome.
632 // To avoid this, don't restore on startup but instead show the crashed
633 // infobar.
634 VLOG(1) << "Unclean exit; not processing";
635 return false;
638 uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
639 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
640 CommandLine::ForCurrentProcess()->HasSwitch(
641 switches::kCreateBrowserOnStartupForTests)) {
642 restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
645 #if defined(OS_MACOSX)
646 // On Mac, when restoring a session with no windows, suppress the creation
647 // of a new window in the case where the system is launching Chrome via a
648 // login item or Lion's resume feature.
649 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
650 restore_behavior = restore_behavior &
651 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
653 #endif
655 // Pause the StartupTimer. Since the restore here is synchronous, we can
656 // keep these two metrics (browser startup time and session restore time)
657 // separate.
658 performance_monitor::StartupTimer::PauseTimer();
660 // The startup code only executes for browsers launched in desktop mode.
661 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
662 Browser* browser = SessionRestore::RestoreSession(
663 profile_, NULL, desktop_type, restore_behavior,
664 urls_to_open);
666 performance_monitor::StartupTimer::UnpauseTimer();
668 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
669 return true;
672 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
673 if (!browser)
674 return false;
676 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
678 // Session restore may occur if the startup preference is "last" or if the
679 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
680 // to start deleting leftover data.
681 if (pref.type != SessionStartupPref::LAST &&
682 !HasPendingUncleanExit(profile_)) {
683 content::BrowserContext::GetDefaultStoragePartition(profile_)->
684 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
687 return true;
690 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
691 const std::vector<GURL>& urls_to_open,
692 chrome::HostDesktopType desktop_type) {
693 SessionStartupPref pref =
694 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
695 StartupTabs tabs;
696 // Pinned tabs should not be displayed when chrome is launched in incognito
697 // mode. Also, no pages should be opened automatically if the session
698 // crashed. Otherwise it might trigger another crash, locking the user out of
699 // chrome. The crash infobar is shown in this case.
700 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
701 profile_->GetPrefs()) &&
702 !HasPendingUncleanExit(profile_)) {
703 tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
706 RecordAppLaunches(profile_, urls_to_open, tabs);
708 if (!urls_to_open.empty()) {
709 // If urls were specified on the command line, use them.
710 UrlsToTabs(urls_to_open, &tabs);
711 } else if (pref.type == SessionStartupPref::DEFAULT ||
712 (is_first_run_ &&
713 browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
714 std::vector<GURL> urls;
715 AddStartupURLs(&urls);
716 UrlsToTabs(urls, &tabs);
717 } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
718 !HasPendingUncleanExit(profile_)) {
719 // Only use the set of urls specified in preferences if nothing was
720 // specified on the command line. Filter out any urls that are to be
721 // restored by virtue of having been previously pinned.
722 AddUniqueURLs(pref.urls, &tabs);
723 } else if (pref.type == SessionStartupPref::HOMEPAGE) {
724 // If 'homepage' selected, either by the user or by a policy, we should
725 // have migrated them to another value.
726 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
729 if (tabs.empty())
730 return NULL;
732 Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
733 return browser;
736 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
737 StartupTabs* tabs) {
738 size_t num_existing_tabs = tabs->size();
739 for (size_t i = 0; i < urls.size(); ++i) {
740 bool in_tabs = false;
741 for (size_t j = 0; j < num_existing_tabs; ++j) {
742 if (urls[i] == (*tabs)[j].url) {
743 in_tabs = true;
744 break;
747 if (!in_tabs) {
748 StartupTab tab;
749 tab.is_pinned = false;
750 tab.url = urls[i];
751 tabs->push_back(tab);
756 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
757 Browser* browser,
758 bool process_startup,
759 const std::vector<GURL>& urls,
760 chrome::HostDesktopType desktop_type) {
761 StartupTabs tabs;
762 UrlsToTabs(urls, &tabs);
763 return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
766 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
767 Browser* browser,
768 bool process_startup,
769 const StartupTabs& tabs,
770 chrome::HostDesktopType desktop_type) {
771 DCHECK(!tabs.empty());
773 // If we don't yet have a profile, try to use the one we're given from
774 // |browser|. While we may not end up actually using |browser| (since it
775 // could be a popup window), we can at least use the profile.
776 if (!profile_ && browser)
777 profile_ = browser->profile();
779 if (!browser || !browser->is_type_tabbed())
780 browser = new Browser(Browser::CreateParams(profile_, desktop_type));
782 bool first_tab = true;
783 ProtocolHandlerRegistry* registry = profile_ ?
784 ProtocolHandlerRegistryFactory::GetForProfile(profile_) : NULL;
785 for (size_t i = 0; i < tabs.size(); ++i) {
786 // We skip URLs that we'd have to launch an external protocol handler for.
787 // This avoids us getting into an infinite loop asking ourselves to open
788 // a URL, should the handler be (incorrectly) configured to be us. Anyone
789 // asking us to open such a URL should really ask the handler directly.
790 bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
791 (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
792 if (!process_startup && !handled_by_chrome)
793 continue;
795 int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
796 TabStripModel::ADD_NONE;
797 add_types |= TabStripModel::ADD_FORCE_INDEX;
798 if (tabs[i].is_pinned)
799 add_types |= TabStripModel::ADD_PINNED;
801 chrome::NavigateParams params(browser, tabs[i].url,
802 content::PAGE_TRANSITION_AUTO_TOPLEVEL);
803 params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
804 params.tabstrip_add_types = add_types;
805 params.extension_app_id = tabs[i].app_id;
807 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
808 if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
809 params.extra_headers = RLZTracker::GetAccessPointHttpHeader(
810 RLZTracker::CHROME_HOME_PAGE);
812 #endif // defined(ENABLE_RLZ) && !defined(OS_IOS)
814 chrome::Navigate(&params);
816 first_tab = false;
818 if (!browser->tab_strip_model()->GetActiveWebContents()) {
819 // TODO: this is a work around for 110909. Figure out why it's needed.
820 if (!browser->tab_strip_model()->count())
821 chrome::AddTabAt(browser, GURL(), -1, true);
822 else
823 browser->tab_strip_model()->ActivateTabAt(0, false);
826 // The default behavior is to show the window, as expressed by the default
827 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
828 // to true ahead of this place, it means another task must have been spawned
829 // to take care of that.
830 if (!browser_creator_ || browser_creator_->show_main_browser_window())
831 browser->window()->Show();
833 // In kiosk mode, we want to always be fullscreen, so switch to that now.
834 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
835 CommandLine::ForCurrentProcess()->HasSwitch(switches::kStartFullscreen))
836 chrome::ToggleFullscreenMode(browser);
838 return browser;
841 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
842 Browser* browser,
843 chrome::startup::IsProcessStartup is_process_startup) {
844 if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
845 return;
847 if (HasPendingUncleanExit(browser->profile())) {
848 if (!command_line_.HasSwitch(switches::kEnableSessionCrashedBubble) ||
849 !ShowSessionCrashedBubble(browser))
850 SessionCrashedInfoBarDelegate::Create(browser);
853 // The below info bars are only added to the first profile which is launched.
854 // Other profiles might be restoring the browsing sessions asynchronously,
855 // so we cannot add the info bars to the focused tabs here.
856 if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP &&
857 !command_line_.HasSwitch(switches::kTestType)) {
858 chrome::ShowBadFlagsPrompt(browser);
859 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
860 browser->tab_strip_model()->GetActiveWebContents()));
861 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
862 browser->tab_strip_model()->GetActiveWebContents()));
864 #if !defined(OS_CHROMEOS)
865 if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
866 // Generally, the default browser prompt should not be shown on first
867 // run. However, when the set-as-default dialog has been suppressed, we
868 // need to allow it.
869 if ((!is_first_run_ ||
870 (browser_creator_ &&
871 browser_creator_->is_default_browser_dialog_suppressed())) &&
872 !chrome::ShowAutolaunchPrompt(browser)) {
873 chrome::ShowDefaultBrowserPrompt(profile_,
874 browser->host_desktop_type());
877 #endif
881 void StartupBrowserCreatorImpl::AddStartupURLs(
882 std::vector<GURL>* startup_urls) const {
883 // TODO(atwilson): Simplify the logic that decides which tabs to open on
884 // start-up and make it more consistent. http://crbug.com/248883
886 // If we have urls specified by the first run master preferences use them
887 // and nothing else.
888 if (browser_creator_ && startup_urls->empty()) {
889 if (!browser_creator_->first_run_tabs_.empty()) {
890 std::vector<GURL>::iterator it =
891 browser_creator_->first_run_tabs_.begin();
892 while (it != browser_creator_->first_run_tabs_.end()) {
893 // Replace magic names for the actual urls.
894 if (it->host() == "new_tab_page") {
895 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
896 } else if (it->host() == "welcome_page") {
897 startup_urls->push_back(internals::GetWelcomePageURL());
898 } else {
899 startup_urls->push_back(*it);
901 ++it;
903 browser_creator_->first_run_tabs_.clear();
907 // Otherwise open at least the new tab page (and the welcome page, if this
908 // is the first time the browser is being started), or the set of URLs
909 // specified on the command line.
910 if (startup_urls->empty()) {
911 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
912 if (first_run::ShouldShowWelcomePage())
913 startup_urls->push_back(internals::GetWelcomePageURL());
916 if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
917 signin::DidShowPromoAtStartup(profile_);
919 const GURL sync_promo_url = signin::GetPromoURL(signin::SOURCE_START_PAGE,
920 false);
922 // No need to add if the sync promo is already in the startup list.
923 bool add_promo = true;
924 for (std::vector<GURL>::const_iterator it = startup_urls->begin();
925 it != startup_urls->end(); ++it) {
926 if (*it == sync_promo_url) {
927 add_promo = false;
928 break;
932 if (add_promo) {
933 // If the first URL is the NTP, replace it with the sync promo. This
934 // behavior is desired because completing or skipping the sync promo
935 // causes a redirect to the NTP.
936 if (!startup_urls->empty() && IsNewTabURL(profile_, startup_urls->at(0)))
937 startup_urls->at(0) = sync_promo_url;
938 else
939 startup_urls->insert(startup_urls->begin(), sync_promo_url);