Infobar material design refresh: layout
[chromium-blink-merge.git] / chrome / browser / ui / startup / startup_browser_creator_impl.cc
blobecbc5dc81b1829f603ecab69608efbbcdea3efe3
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_macros.h"
20 #include "base/metrics/statistics_recorder.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/threading/thread_restrictions.h"
28 #include "chrome/browser/apps/install_chrome_app.h"
29 #include "chrome/browser/auto_launch_trial.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/chrome_notification_types.h"
32 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
33 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
34 #include "chrome/browser/defaults.h"
35 #include "chrome/browser/extensions/extension_creator.h"
36 #include "chrome/browser/extensions/extension_util.h"
37 #include "chrome/browser/extensions/launch_util.h"
38 #include "chrome/browser/extensions/pack_extension_job.h"
39 #include "chrome/browser/first_run/first_run.h"
40 #include "chrome/browser/infobars/infobar_service.h"
41 #include "chrome/browser/prefs/incognito_mode_prefs.h"
42 #include "chrome/browser/prefs/session_startup_pref.h"
43 #include "chrome/browser/profiles/profile.h"
44 #include "chrome/browser/profiles/profile_io_data.h"
45 #include "chrome/browser/sessions/session_restore.h"
46 #include "chrome/browser/sessions/session_service.h"
47 #include "chrome/browser/sessions/session_service_factory.h"
48 #include "chrome/browser/shell_integration.h"
49 #include "chrome/browser/signin/signin_promo.h"
50 #include "chrome/browser/ui/app_list/app_list_service.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_navigator.h"
55 #include "chrome/browser/ui/browser_tabrestore.h"
56 #include "chrome/browser/ui/browser_tabstrip.h"
57 #include "chrome/browser/ui/browser_window.h"
58 #include "chrome/browser/ui/extensions/app_launch_params.h"
59 #include "chrome/browser/ui/extensions/application_launch.h"
60 #include "chrome/browser/ui/host_desktop.h"
61 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
62 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
63 #include "chrome/browser/ui/startup/default_browser_prompt.h"
64 #include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
65 #include "chrome/browser/ui/startup/obsolete_system_infobar_delegate.h"
66 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
67 #include "chrome/browser/ui/startup/startup_browser_creator.h"
68 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
69 #include "chrome/browser/ui/tabs/tab_strip_model.h"
70 #include "chrome/common/chrome_constants.h"
71 #include "chrome/common/chrome_paths.h"
72 #include "chrome/common/chrome_result_codes.h"
73 #include "chrome/common/chrome_switches.h"
74 #include "chrome/common/extensions/extension_constants.h"
75 #include "chrome/common/extensions/extension_metrics.h"
76 #include "chrome/common/pref_names.h"
77 #include "chrome/common/url_constants.h"
78 #include "chrome/grit/locale_settings.h"
79 #include "chrome/installer/util/browser_distribution.h"
80 #include "components/google/core/browser/google_util.h"
81 #include "components/rappor/rappor_utils.h"
82 #include "content/public/browser/child_process_security_policy.h"
83 #include "content/public/browser/dom_storage_context.h"
84 #include "content/public/browser/notification_observer.h"
85 #include "content/public/browser/notification_registrar.h"
86 #include "content/public/browser/storage_partition.h"
87 #include "content/public/browser/web_contents.h"
88 #include "extensions/browser/extension_prefs.h"
89 #include "extensions/browser/extension_registry.h"
90 #include "extensions/common/constants.h"
91 #include "extensions/common/extension.h"
92 #include "extensions/common/extension_set.h"
93 #include "net/base/network_change_notifier.h"
94 #include "ui/base/l10n/l10n_util.h"
96 #if defined(OS_MACOSX)
97 #include "base/mac/mac_util.h"
98 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
99 #endif
101 #if defined(OS_WIN)
102 #include "base/win/windows_version.h"
103 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
104 #endif
106 #if defined(ENABLE_RLZ)
107 #include "components/rlz/rlz_tracker.h"
108 #endif
110 using content::ChildProcessSecurityPolicy;
111 using content::WebContents;
112 using extensions::Extension;
114 namespace {
116 // Utility functions ----------------------------------------------------------
118 enum LaunchMode {
119 LM_TO_BE_DECIDED = 0, // Possibly direct launch or via a shortcut.
120 LM_AS_WEBAPP, // Launched as a installed web application.
121 LM_WITH_URLS, // Launched with urls in the cmd line.
122 LM_SHORTCUT_NONE, // Not launched from a shortcut.
123 LM_SHORTCUT_NONAME, // Launched from shortcut but no name available.
124 LM_SHORTCUT_UNKNOWN, // Launched from user-defined shortcut.
125 LM_SHORTCUT_QUICKLAUNCH, // Launched from the quick launch bar.
126 LM_SHORTCUT_DESKTOP, // Launched from a desktop shortcut.
127 LM_SHORTCUT_TASKBAR, // Launched from the taskbar.
128 LM_LINUX_MAC_BEOS // Other OS buckets start here.
131 #if defined(OS_WIN)
132 // Undocumented flag in the startup info structure tells us what shortcut was
133 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
134 // more information. Confirmed to work on XP, Vista and Win7.
135 LaunchMode GetLaunchShortcutKind() {
136 STARTUPINFOW si = { sizeof(si) };
137 GetStartupInfoW(&si);
138 if (si.dwFlags & 0x800) {
139 if (!si.lpTitle)
140 return LM_SHORTCUT_NONAME;
141 base::string16 shortcut(si.lpTitle);
142 // The windows quick launch path is not localized.
143 if (shortcut.find(L"\\Quick Launch\\") != base::string16::npos) {
144 if (base::win::GetVersion() >= base::win::VERSION_WIN7)
145 return LM_SHORTCUT_TASKBAR;
146 else
147 return LM_SHORTCUT_QUICKLAUNCH;
149 scoped_ptr<base::Environment> env(base::Environment::Create());
150 std::string appdata_path;
151 env->GetVar("USERPROFILE", &appdata_path);
152 if (!appdata_path.empty() &&
153 shortcut.find(base::ASCIIToUTF16(appdata_path)) != base::string16::npos)
154 return LM_SHORTCUT_DESKTOP;
155 return LM_SHORTCUT_UNKNOWN;
157 return LM_SHORTCUT_NONE;
159 #else
160 // TODO(cpu): Port to other platforms.
161 LaunchMode GetLaunchShortcutKind() {
162 return LM_LINUX_MAC_BEOS;
164 #endif
166 // Log in a histogram the frequency of launching by the different methods. See
167 // LaunchMode enum for the actual values of the buckets.
168 void RecordLaunchModeHistogram(LaunchMode mode) {
169 int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
170 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
173 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
174 for (size_t i = 0; i < urls.size(); ++i) {
175 StartupTab tab;
176 tab.is_pinned = false;
177 tab.url = urls[i];
178 tabs->push_back(tab);
182 // Return true if the command line option --app-id is used. Set
183 // |out_extension| to the app to open, and |out_launch_container|
184 // to the type of window into which the app should be open.
185 bool GetAppLaunchContainer(
186 Profile* profile,
187 const std::string& app_id,
188 const Extension** out_extension,
189 extensions::LaunchContainer* out_launch_container) {
191 const Extension* extension = extensions::ExtensionRegistry::Get(
192 profile)->enabled_extensions().GetByID(app_id);
193 // The extension with id |app_id| may have been uninstalled.
194 if (!extension)
195 return false;
197 // Don't launch platform apps in incognito mode.
198 if (profile->IsOffTheRecord() && extension->is_platform_app())
199 return false;
201 // Look at preferences to find the right launch container. If no
202 // preference is set, launch as a window.
203 extensions::LaunchContainer launch_container = extensions::GetLaunchContainer(
204 extensions::ExtensionPrefs::Get(profile), extension);
206 if (!extensions::util::IsNewBookmarkAppsEnabled() &&
207 !extensions::HasPreferredLaunchContainer(
208 extensions::ExtensionPrefs::Get(profile), extension)) {
209 launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
212 *out_extension = extension;
213 *out_launch_container = launch_container;
214 return true;
217 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
218 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_APP,
219 app_type);
222 void RecordAppLaunches(Profile* profile,
223 const std::vector<GURL>& cmd_line_urls,
224 const StartupTabs& autolaunch_tabs) {
225 const extensions::ExtensionSet& extensions =
226 extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
227 for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
228 const extensions::Extension* extension =
229 extensions.GetAppByURL(cmd_line_urls.at(i));
230 if (extension) {
231 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_URL,
232 extension->GetType());
235 for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
236 const extensions::Extension* extension =
237 extensions.GetAppByURL(autolaunch_tabs.at(i).url);
238 if (extension) {
239 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_AUTOLAUNCH,
240 extension->GetType());
245 // TODO(koz): Consolidate this function and remove the special casing.
246 const Extension* GetPlatformApp(Profile* profile,
247 const std::string& extension_id) {
248 const Extension* extension =
249 extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
250 extension_id, extensions::ExtensionRegistry::EVERYTHING);
251 return extension && extension->is_platform_app() ? extension : NULL;
254 } // namespace
256 namespace internals {
258 GURL GetWelcomePageURL() {
259 std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
260 return GURL(welcome_url);
263 } // namespace internals
265 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
266 const base::FilePath& cur_dir,
267 const base::CommandLine& command_line,
268 chrome::startup::IsFirstRun is_first_run)
269 : cur_dir_(cur_dir),
270 command_line_(command_line),
271 profile_(NULL),
272 browser_creator_(NULL),
273 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN),
274 welcome_run_type_(WelcomeRunType::NONE) {
277 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
278 const base::FilePath& cur_dir,
279 const base::CommandLine& command_line,
280 StartupBrowserCreator* browser_creator,
281 chrome::startup::IsFirstRun is_first_run)
282 : cur_dir_(cur_dir),
283 command_line_(command_line),
284 profile_(NULL),
285 browser_creator_(browser_creator),
286 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN),
287 welcome_run_type_(WelcomeRunType::NONE) {
290 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
293 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
294 const std::vector<GURL>& urls_to_open,
295 bool process_startup,
296 chrome::HostDesktopType desktop_type) {
297 UMA_HISTOGRAM_COUNTS_100("Startup.BrowserLaunchURLCount",
298 static_cast<base::HistogramBase::Sample>(urls_to_open.size()));
299 RecordRapporOnStartupURLs(urls_to_open);
301 DCHECK(profile);
302 profile_ = profile;
304 if (AppListService::HandleLaunchCommandLine(command_line_, profile))
305 return true;
307 if (command_line_.HasSwitch(switches::kAppId)) {
308 std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
309 const Extension* extension = GetPlatformApp(profile, app_id);
310 // If |app_id| is a disabled or terminated platform app we handle it
311 // specially here, otherwise it will be handled below.
312 if (extension) {
313 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
314 AppLaunchParams params(profile, extension,
315 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW,
316 extensions::SOURCE_COMMAND_LINE);
317 params.command_line = command_line_;
318 params.current_directory = cur_dir_;
319 // If we are being launched from the command line, default to native
320 // desktop.
321 params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
322 ::OpenApplicationWithReenablePrompt(params);
323 return true;
327 // Open the required browser windows and tabs. First, see if
328 // we're being run as an application window. If so, the user
329 // opened an app shortcut. Don't restore tabs or open initial
330 // URLs in that case. The user should see the window as an app,
331 // not as chrome.
332 // Special case is when app switches are passed but we do want to restore
333 // session. In that case open app window + focus it after session is restored.
334 if (OpenApplicationWindow(profile)) {
335 RecordLaunchModeHistogram(LM_AS_WEBAPP);
336 } else {
337 RecordLaunchModeHistogram(urls_to_open.empty() ?
338 LM_TO_BE_DECIDED : LM_WITH_URLS);
340 ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
342 if (command_line_.HasSwitch(switches::kInstallChromeApp)) {
343 install_chrome_app::InstallChromeApp(
344 command_line_.GetSwitchValueASCII(switches::kInstallChromeApp));
347 // If this is an app launch, but we didn't open an app window, it may
348 // be an app tab.
349 OpenApplicationTab(profile);
351 #if defined(OS_MACOSX)
352 if (process_startup) {
353 // Check whether the auto-update system needs to be promoted from user
354 // to system.
355 KeystoneInfoBar::PromotionInfoBar(profile);
357 #endif
360 // In kiosk mode, we want to always be fullscreen, so switch to that now.
361 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
362 base::CommandLine::ForCurrentProcess()->HasSwitch(
363 switches::kStartFullscreen)) {
364 // It's possible for there to be no browser window, e.g. if someone
365 // specified a non-sensical combination of options
366 // ("--kiosk --no_startup_window"); do nothing in that case.
367 Browser* browser = BrowserList::GetInstance(desktop_type)->GetLastActive();
368 if (browser)
369 chrome::ToggleFullscreenMode(browser);
372 #if defined(OS_WIN)
373 if (process_startup)
374 ShellIntegration::MigrateChromiumShortcuts();
375 #endif // defined(OS_WIN)
377 return true;
380 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
381 std::string* app_id) {
382 if (command_line_.HasSwitch(switches::kApp)) {
383 if (app_url)
384 *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
385 return true;
387 if (command_line_.HasSwitch(switches::kAppId)) {
388 if (app_id)
389 *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
390 return true;
392 return false;
395 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
396 std::string app_id;
397 // App shortcuts to URLs always open in an app window. Because this
398 // function will open an app that should be in a tab, there is no need
399 // to look at the app URL. OpenApplicationWindow() will open app url
400 // shortcuts.
401 if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
402 return false;
404 extensions::LaunchContainer launch_container;
405 const Extension* extension;
406 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
407 return false;
409 // If the user doesn't want to open a tab, fail.
410 if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
411 return false;
413 RecordCmdLineAppHistogram(extension->GetType());
415 WebContents* app_tab = ::OpenApplication(
416 AppLaunchParams(profile, extension, extensions::LAUNCH_CONTAINER_TAB,
417 NEW_FOREGROUND_TAB, extensions::SOURCE_COMMAND_LINE));
418 return (app_tab != NULL);
421 bool StartupBrowserCreatorImpl::OpenApplicationWindow(Profile* profile) {
422 std::string url_string, app_id;
423 if (!IsAppLaunch(&url_string, &app_id))
424 return false;
426 // This can fail if the app_id is invalid. It can also fail if the
427 // extension is external, and has not yet been installed.
428 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
429 // Open an URL to the gallery page of the extension id?
430 if (!app_id.empty()) {
431 extensions::LaunchContainer launch_container;
432 const Extension* extension;
433 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
434 return false;
436 // TODO(skerner): Could pass in |extension| and |launch_container|,
437 // and avoid calling GetAppLaunchContainer() both here and in
438 // OpenApplicationTab().
440 if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
441 return false;
443 RecordCmdLineAppHistogram(extension->GetType());
445 AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW,
446 extensions::SOURCE_COMMAND_LINE);
447 params.command_line = command_line_;
448 params.current_directory = cur_dir_;
449 WebContents* tab_in_app_window = ::OpenApplication(params);
451 // Platform apps fire off a launch event which may or may not open a window.
452 return (tab_in_app_window != NULL || CanLaunchViaEvent(extension));
455 if (url_string.empty())
456 return false;
458 #if defined(OS_WIN) // Fix up Windows shortcuts.
459 base::ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
460 #endif
461 GURL url(url_string);
463 // Restrict allowed URLs for --app switch.
464 if (!url.is_empty() && url.is_valid()) {
465 ChildProcessSecurityPolicy* policy =
466 ChildProcessSecurityPolicy::GetInstance();
467 if (policy->IsWebSafeScheme(url.scheme()) ||
468 url.SchemeIs(url::kFileScheme)) {
469 const extensions::Extension* extension =
470 extensions::ExtensionRegistry::Get(profile)
471 ->enabled_extensions().GetAppByURL(url);
472 if (extension) {
473 RecordCmdLineAppHistogram(extension->GetType());
474 } else {
475 extensions::RecordAppLaunchType(
476 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
477 extensions::Manifest::TYPE_HOSTED_APP);
480 WebContents* app_tab = ::OpenAppShortcutWindow(profile, url);
481 return (app_tab != NULL);
484 return false;
487 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
488 bool process_startup,
489 const std::vector<GURL>& urls_to_open,
490 chrome::HostDesktopType desktop_type) {
491 // If we're starting up in "background mode" (no open browser window) then
492 // don't open any browser windows, unless kAutoLaunchAtStartup is also
493 // specified.
494 if (process_startup &&
495 command_line_.HasSwitch(switches::kNoStartupWindow) &&
496 !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
497 return;
500 // Determine whether or not this launch must include the welcome page.
501 InitializeWelcomeRunType(urls_to_open);
503 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
504 #if defined(OS_WIN)
505 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
506 // See if there are apps for this profile that should be launched on startup
507 // due to a switch from Metro mode.
508 app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
510 #endif
512 if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
513 // ProcessStartupURLs processed the urls, nothing else to do.
514 return;
517 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
518 chrome::startup::IS_PROCESS_STARTUP :
519 chrome::startup::IS_NOT_PROCESS_STARTUP;
520 if (!process_startup) {
521 // Even if we're not starting a new process, this may conceptually be
522 // "startup" for the user and so should be handled in a similar way. Eg.,
523 // Chrome may have been running in the background due to an app with a
524 // background page being installed, or running with only an app window
525 // displayed.
526 SessionService* service =
527 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
528 if (service && service->ShouldNewWindowStartSession()) {
529 // Restore the last session if any, optionally including the welcome page
530 // if desired.
531 if (!HasPendingUncleanExit(profile_)) {
532 std::vector<GURL> adjusted_urls(urls_to_open);
533 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB) {
534 adjusted_urls.insert(adjusted_urls.begin(),
535 internals::GetWelcomePageURL());
537 if (service->RestoreIfNecessary(adjusted_urls))
538 return;
541 // Open user-specified URLs like pinned tabs and startup tabs.
542 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
543 if (browser) {
544 AddInfoBarsIfNecessary(browser, is_process_startup);
545 return;
550 // Session startup didn't occur, open the urls.
551 Browser* browser = NULL;
552 std::vector<GURL> adjusted_urls = urls_to_open;
553 if (adjusted_urls.empty()) {
554 AddStartupURLs(&adjusted_urls);
555 } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
556 // Always open a list of urls in a window on the native desktop.
557 browser = chrome::FindTabbedBrowser(profile_, false,
558 chrome::HOST_DESKTOP_TYPE_NATIVE);
560 // This will launch a browser; prevent session restore.
561 StartupBrowserCreator::in_synchronous_profile_launch_ = true;
562 browser =
563 OpenURLsInBrowser(browser, process_startup, adjusted_urls, desktop_type);
564 StartupBrowserCreator::in_synchronous_profile_launch_ = false;
565 AddInfoBarsIfNecessary(browser, is_process_startup);
568 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
569 const std::vector<GURL>& urls_to_open,
570 chrome::HostDesktopType desktop_type) {
571 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
572 SessionStartupPref pref =
573 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
574 if (pref.type == SessionStartupPref::LAST)
575 VLOG(1) << "Pref: last";
576 else if (pref.type == SessionStartupPref::URLS)
577 VLOG(1) << "Pref: urls";
578 else if (pref.type == SessionStartupPref::DEFAULT)
579 VLOG(1) << "Pref: default";
581 apps::AppRestoreService* restore_service =
582 apps::AppRestoreServiceFactory::GetForProfile(profile_);
583 // NULL in incognito mode.
584 if (restore_service) {
585 restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
586 StartupBrowserCreator::WasRestarted()));
589 if (pref.type == SessionStartupPref::LAST) {
590 if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
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
595 // infobar.
596 VLOG(1) << "Unclean exit; not processing";
597 return false;
600 uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
601 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
602 base::CommandLine::ForCurrentProcess()->HasSwitch(
603 switches::kCreateBrowserOnStartupForTests)) {
604 restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
607 #if defined(OS_MACOSX)
608 // On Mac, when restoring a session with no windows, suppress the creation
609 // of a new window in the case where the system is launching Chrome via a
610 // login item or Lion's resume feature.
611 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
612 restore_behavior = restore_behavior &
613 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
615 #endif
617 // Optionally include the welcome page.
618 std::vector<GURL> adjusted_urls(urls_to_open);
619 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB) {
620 adjusted_urls.insert(adjusted_urls.begin(),
621 internals::GetWelcomePageURL());
624 // The startup code only executes for browsers launched in desktop mode.
625 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
626 Browser* browser = SessionRestore::RestoreSession(
627 profile_, NULL, desktop_type, restore_behavior, adjusted_urls);
629 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
630 return true;
633 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
634 if (!browser)
635 return false;
637 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
639 // Session restore may occur if the startup preference is "last" or if the
640 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
641 // to start deleting leftover data.
642 if (pref.type != SessionStartupPref::LAST &&
643 !HasPendingUncleanExit(profile_)) {
644 content::BrowserContext::GetDefaultStoragePartition(profile_)->
645 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
648 return true;
651 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
652 const std::vector<GURL>& urls_to_open,
653 chrome::HostDesktopType desktop_type) {
654 SessionStartupPref pref =
655 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
656 StartupTabs tabs;
657 // Pinned tabs should not be displayed when chrome is launched in incognito
658 // mode. Also, no pages should be opened automatically if the session
659 // crashed. Otherwise it might trigger another crash, locking the user out of
660 // chrome. The crash infobar is shown in this case.
661 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
662 profile_->GetPrefs()) &&
663 !HasPendingUncleanExit(profile_)) {
664 tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
667 RecordAppLaunches(profile_, urls_to_open, tabs);
669 if (!urls_to_open.empty()) {
670 // If urls were specified on the command line, use them.
671 UrlsToTabs(urls_to_open, &tabs);
672 } else if (pref.type == SessionStartupPref::DEFAULT ||
673 (is_first_run_ &&
674 browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
675 std::vector<GURL> urls;
676 AddStartupURLs(&urls);
677 UrlsToTabs(urls, &tabs);
678 } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
679 !HasPendingUncleanExit(profile_)) {
680 // Optionally include the welcome page first.
681 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB)
682 UrlsToTabs(std::vector<GURL>(1, internals::GetWelcomePageURL()), &tabs);
683 // Only use the set of urls specified in preferences if nothing was
684 // specified on the command line. Filter out any urls that are to be
685 // restored by virtue of having been previously pinned.
686 AddUniqueURLs(pref.urls, &tabs);
687 } else if (pref.type == SessionStartupPref::HOMEPAGE) {
688 // If 'homepage' selected, either by the user or by a policy, we should
689 // have migrated them to another value.
690 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
693 if (tabs.empty())
694 return NULL;
696 Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
697 return browser;
700 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
701 StartupTabs* tabs) {
702 size_t num_existing_tabs = tabs->size();
703 for (size_t i = 0; i < urls.size(); ++i) {
704 bool in_tabs = false;
705 for (size_t j = 0; j < num_existing_tabs; ++j) {
706 if (urls[i] == (*tabs)[j].url) {
707 in_tabs = true;
708 break;
711 if (!in_tabs) {
712 StartupTab tab;
713 tab.is_pinned = false;
714 tab.url = urls[i];
715 tabs->push_back(tab);
720 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
721 Browser* browser,
722 bool process_startup,
723 const std::vector<GURL>& urls,
724 chrome::HostDesktopType desktop_type) {
725 StartupTabs tabs;
726 UrlsToTabs(urls, &tabs);
727 return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
730 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
731 Browser* browser,
732 bool process_startup,
733 const StartupTabs& tabs,
734 chrome::HostDesktopType desktop_type) {
735 DCHECK(!tabs.empty());
737 // If we don't yet have a profile, try to use the one we're given from
738 // |browser|. While we may not end up actually using |browser| (since it
739 // could be a popup window), we can at least use the profile.
740 if (!profile_ && browser)
741 profile_ = browser->profile();
743 if (!browser || !browser->is_type_tabbed())
744 browser = new Browser(Browser::CreateParams(profile_, desktop_type));
746 bool first_tab = true;
747 ProtocolHandlerRegistry* registry = profile_ ?
748 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_) : NULL;
749 for (size_t i = 0; i < tabs.size(); ++i) {
750 // We skip URLs that we'd have to launch an external protocol handler for.
751 // This avoids us getting into an infinite loop asking ourselves to open
752 // a URL, should the handler be (incorrectly) configured to be us. Anyone
753 // asking us to open such a URL should really ask the handler directly.
754 bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
755 (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
756 if (!process_startup && !handled_by_chrome)
757 continue;
759 int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
760 TabStripModel::ADD_NONE;
761 add_types |= TabStripModel::ADD_FORCE_INDEX;
762 if (tabs[i].is_pinned)
763 add_types |= TabStripModel::ADD_PINNED;
765 chrome::NavigateParams params(browser, tabs[i].url,
766 ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
767 params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
768 params.tabstrip_add_types = add_types;
770 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
771 if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
772 params.extra_headers = rlz::RLZTracker::GetAccessPointHttpHeader(
773 rlz::RLZTracker::ChromeHomePage());
775 #endif // defined(ENABLE_RLZ) && !defined(OS_IOS)
777 chrome::Navigate(&params);
779 first_tab = false;
781 if (!browser->tab_strip_model()->GetActiveWebContents()) {
782 // TODO(sky): this is a work around for 110909. Figure out why it's needed.
783 if (!browser->tab_strip_model()->count())
784 chrome::AddTabAt(browser, GURL(), -1, true);
785 else
786 browser->tab_strip_model()->ActivateTabAt(0, false);
789 // The default behavior is to show the window, as expressed by the default
790 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
791 // to true ahead of this place, it means another task must have been spawned
792 // to take care of that.
793 if (!browser_creator_ || browser_creator_->show_main_browser_window())
794 browser->window()->Show();
796 return browser;
799 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
800 Browser* browser,
801 chrome::startup::IsProcessStartup is_process_startup) {
802 if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
803 return;
805 if (HasPendingUncleanExit(browser->profile()) &&
806 !browser->window()->ShowSessionCrashedBubble()) {
807 SessionCrashedInfoBarDelegate::Create(browser);
810 // The below info bars are only added to the first profile which is launched.
811 // Other profiles might be restoring the browsing sessions asynchronously,
812 // so we cannot add the info bars to the focused tabs here.
813 if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP &&
814 !command_line_.HasSwitch(switches::kTestType)) {
815 chrome::ShowBadFlagsPrompt(browser);
816 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
817 browser->tab_strip_model()->GetActiveWebContents()));
818 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
819 browser->tab_strip_model()->GetActiveWebContents()));
821 #if !defined(OS_CHROMEOS)
822 if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
823 // Generally, the default browser prompt should not be shown on first
824 // run. However, when the set-as-default dialog has been suppressed, we
825 // need to allow it.
826 if ((!is_first_run_ ||
827 (browser_creator_ &&
828 browser_creator_->is_default_browser_dialog_suppressed())) &&
829 !chrome::ShowAutolaunchPrompt(browser)) {
830 chrome::ShowDefaultBrowserPrompt(profile_,
831 browser->host_desktop_type());
834 #endif
838 void StartupBrowserCreatorImpl::AddStartupURLs(
839 std::vector<GURL>* startup_urls) const {
840 // TODO(atwilson): Simplify the logic that decides which tabs to open on
841 // start-up and make it more consistent. http://crbug.com/248883
843 // If we have urls specified by the first run master preferences use them
844 // and nothing else.
845 if (browser_creator_ && startup_urls->empty()) {
846 if (!browser_creator_->first_run_tabs_.empty()) {
847 std::vector<GURL>::iterator it =
848 browser_creator_->first_run_tabs_.begin();
849 while (it != browser_creator_->first_run_tabs_.end()) {
850 // Replace magic names for the actual urls.
851 if (it->host() == "new_tab_page") {
852 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
853 } else if (it->host() == "welcome_page") {
854 startup_urls->push_back(internals::GetWelcomePageURL());
855 } else {
856 startup_urls->push_back(*it);
858 ++it;
860 browser_creator_->first_run_tabs_.clear();
864 // Otherwise open at least the new tab page (and optionally the welcome page
865 // at the front or back as indicated by welcome_run_type_), or the set of URLs
866 // specified on the command line.
867 if (startup_urls->empty()) {
868 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB)
869 startup_urls->push_back(internals::GetWelcomePageURL());
870 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
871 if (welcome_run_type_ == WelcomeRunType::FIRST_RUN_LAST_TAB)
872 startup_urls->push_back(internals::GetWelcomePageURL());
875 if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
876 signin::DidShowPromoAtStartup(profile_);
878 const GURL sync_promo_url = signin::GetPromoURL(
879 signin_metrics::SOURCE_START_PAGE, false);
881 // No need to add if the sync promo is already in the startup list.
882 bool add_promo = true;
883 for (std::vector<GURL>::const_iterator it = startup_urls->begin();
884 it != startup_urls->end(); ++it) {
885 if (*it == sync_promo_url) {
886 add_promo = false;
887 break;
891 if (add_promo) {
892 // If the first URL is the NTP, replace it with the sync promo. This
893 // behavior is desired because completing or skipping the sync promo
894 // causes a redirect to the NTP.
895 if (!startup_urls->empty() &&
896 startup_urls->at(0) == GURL(chrome::kChromeUINewTabURL))
897 startup_urls->at(0) = sync_promo_url;
898 else
899 startup_urls->insert(startup_urls->begin(), sync_promo_url);
904 // For first-run, the type will be FIRST_RUN_LAST for all systems except for
905 // Windows 10+, where it will be FIRST_RUN_FIRST. For non-first run, the type
906 // will be NONE for all systems except for Windows 10+, where it will be
907 // ANY_RUN_FIRST if this is the first somewhat normal launch since an OS
908 // upgrade.
909 void StartupBrowserCreatorImpl::InitializeWelcomeRunType(
910 const std::vector<GURL>& urls_to_open) {
911 DCHECK_EQ(static_cast<int>(WelcomeRunType::NONE),
912 static_cast<int>(welcome_run_type_));
913 #if defined(OS_WIN)
914 // Do not welcome if there are any URLs to open.
915 if (!urls_to_open.empty())
916 return;
918 base::win::OSInfo* const os_info = base::win::OSInfo::GetInstance();
919 const base::win::OSInfo::VersionNumber v(os_info->version_number());
920 const std::string this_version(base::StringPrintf("%d.%d", v.major, v.minor));
921 PrefService* const local_state = g_browser_process->local_state();
923 // Always welcome on first run.
924 if (first_run::ShouldShowWelcomePage()) {
925 // First tab for Win10+, last tab otherwise.
926 welcome_run_type_ = os_info->version() >= base::win::VERSION_WIN10
927 ? WelcomeRunType::FIRST_TAB
928 : WelcomeRunType::FIRST_RUN_LAST_TAB;
929 } else {
930 // Otherwise, do not welcome pre-Win10.
931 if (base::win::GetVersion() < base::win::VERSION_WIN10)
932 return;
934 // Do not welcome if launching into incognito.
935 if (IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
936 profile_->GetPrefs())) {
937 return;
940 // Do not welcome if there is no local state (tests).
941 if (!local_state)
942 return;
944 // Do not welcome if disabled by policy or master_preferences.
945 if (!local_state->GetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled))
946 return;
948 // Do not welcome if already shown for this OS version.
949 if (local_state->GetString(prefs::kLastWelcomedOSVersion) == this_version)
950 return;
952 // Do not welcome if offline.
953 if (net::NetworkChangeNotifier::IsOffline())
954 return;
956 // Do not welcome if Chrome was the default browser at startup.
957 if (g_browser_process->CachedDefaultWebClientState() ==
958 ShellIntegration::IS_DEFAULT) {
959 return;
962 // Show the welcome page in the first tab.
963 welcome_run_type_ = WelcomeRunType::FIRST_TAB;
966 // Remember that the welcome page was shown for this OS version.
967 local_state->SetString(prefs::kLastWelcomedOSVersion, this_version);
968 #else // OS_WIN
969 // Show the welcome page as the last tab only on first-run.
970 if (first_run::ShouldShowWelcomePage())
971 welcome_run_type_ = WelcomeRunType::FIRST_RUN_LAST_TAB;
972 #endif // !OS_WIN
975 void StartupBrowserCreatorImpl::RecordRapporOnStartupURLs(
976 const std::vector<GURL>& urls_to_open) {
977 for (const GURL& url : urls_to_open) {
978 rappor::SampleDomainAndRegistryFromGURL(g_browser_process->rappor_service(),
979 "Startup.BrowserLaunchURL", url);