Update V8 to version 4.6.22.
[chromium-blink-merge.git] / chrome / browser / ui / startup / startup_browser_creator_impl.cc
blob0696d0722384007cb35a11100654e2cd6581e5ab
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/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/net/predictor.h"
42 #include "chrome/browser/notifications/desktop_notification_service.h"
43 #include "chrome/browser/prefs/incognito_mode_prefs.h"
44 #include "chrome/browser/prefs/session_startup_pref.h"
45 #include "chrome/browser/profiles/profile.h"
46 #include "chrome/browser/profiles/profile_io_data.h"
47 #include "chrome/browser/sessions/session_restore.h"
48 #include "chrome/browser/sessions/session_service.h"
49 #include "chrome/browser/sessions/session_service_factory.h"
50 #include "chrome/browser/shell_integration.h"
51 #include "chrome/browser/signin/signin_promo.h"
52 #include "chrome/browser/ui/app_list/app_list_service.h"
53 #include "chrome/browser/ui/browser_commands.h"
54 #include "chrome/browser/ui/browser_finder.h"
55 #include "chrome/browser/ui/browser_list.h"
56 #include "chrome/browser/ui/browser_navigator.h"
57 #include "chrome/browser/ui/browser_tabrestore.h"
58 #include "chrome/browser/ui/browser_tabstrip.h"
59 #include "chrome/browser/ui/browser_window.h"
60 #include "chrome/browser/ui/extensions/app_launch_params.h"
61 #include "chrome/browser/ui/extensions/application_launch.h"
62 #include "chrome/browser/ui/host_desktop.h"
63 #include "chrome/browser/ui/startup/autolaunch_prompt.h"
64 #include "chrome/browser/ui/startup/bad_flags_prompt.h"
65 #include "chrome/browser/ui/startup/default_browser_prompt.h"
66 #include "chrome/browser/ui/startup/google_api_keys_infobar_delegate.h"
67 #include "chrome/browser/ui/startup/obsolete_system_infobar_delegate.h"
68 #include "chrome/browser/ui/startup/session_crashed_infobar_delegate.h"
69 #include "chrome/browser/ui/startup/startup_browser_creator.h"
70 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
71 #include "chrome/browser/ui/tabs/tab_strip_model.h"
72 #include "chrome/common/chrome_constants.h"
73 #include "chrome/common/chrome_paths.h"
74 #include "chrome/common/chrome_result_codes.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/chrome_version_info.h"
77 #include "chrome/common/extensions/extension_constants.h"
78 #include "chrome/common/extensions/extension_metrics.h"
79 #include "chrome/common/pref_names.h"
80 #include "chrome/common/url_constants.h"
81 #include "chrome/grit/locale_settings.h"
82 #include "chrome/installer/util/browser_distribution.h"
83 #include "components/google/core/browser/google_util.h"
84 #include "content/public/browser/child_process_security_policy.h"
85 #include "content/public/browser/dom_storage_context.h"
86 #include "content/public/browser/notification_observer.h"
87 #include "content/public/browser/notification_registrar.h"
88 #include "content/public/browser/storage_partition.h"
89 #include "content/public/browser/web_contents.h"
90 #include "extensions/browser/extension_prefs.h"
91 #include "extensions/browser/extension_registry.h"
92 #include "extensions/common/constants.h"
93 #include "extensions/common/extension.h"
94 #include "extensions/common/extension_set.h"
95 #include "net/base/network_change_notifier.h"
96 #include "ui/base/l10n/l10n_util.h"
98 #if defined(OS_MACOSX)
99 #include "base/mac/mac_util.h"
100 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
101 #endif
103 #if defined(OS_WIN)
104 #include "base/win/windows_version.h"
105 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
106 #endif
108 #if defined(ENABLE_RLZ)
109 #include "components/rlz/rlz_tracker.h"
110 #endif
112 using content::ChildProcessSecurityPolicy;
113 using content::WebContents;
114 using extensions::Extension;
116 namespace {
118 // Utility functions ----------------------------------------------------------
120 enum LaunchMode {
121 LM_TO_BE_DECIDED = 0, // Possibly direct launch or via a shortcut.
122 LM_AS_WEBAPP, // Launched as a installed web application.
123 LM_WITH_URLS, // Launched with urls in the cmd line.
124 LM_SHORTCUT_NONE, // Not launched from a shortcut.
125 LM_SHORTCUT_NONAME, // Launched from shortcut but no name available.
126 LM_SHORTCUT_UNKNOWN, // Launched from user-defined shortcut.
127 LM_SHORTCUT_QUICKLAUNCH, // Launched from the quick launch bar.
128 LM_SHORTCUT_DESKTOP, // Launched from a desktop shortcut.
129 LM_SHORTCUT_TASKBAR, // Launched from the taskbar.
130 LM_LINUX_MAC_BEOS // Other OS buckets start here.
133 #if defined(OS_WIN)
134 // Undocumented flag in the startup info structure tells us what shortcut was
135 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
136 // more information. Confirmed to work on XP, Vista and Win7.
137 LaunchMode GetLaunchShortcutKind() {
138 STARTUPINFOW si = { sizeof(si) };
139 GetStartupInfoW(&si);
140 if (si.dwFlags & 0x800) {
141 if (!si.lpTitle)
142 return LM_SHORTCUT_NONAME;
143 base::string16 shortcut(si.lpTitle);
144 // The windows quick launch path is not localized.
145 if (shortcut.find(L"\\Quick Launch\\") != base::string16::npos) {
146 if (base::win::GetVersion() >= base::win::VERSION_WIN7)
147 return LM_SHORTCUT_TASKBAR;
148 else
149 return LM_SHORTCUT_QUICKLAUNCH;
151 scoped_ptr<base::Environment> env(base::Environment::Create());
152 std::string appdata_path;
153 env->GetVar("USERPROFILE", &appdata_path);
154 if (!appdata_path.empty() &&
155 shortcut.find(base::ASCIIToUTF16(appdata_path)) != base::string16::npos)
156 return LM_SHORTCUT_DESKTOP;
157 return LM_SHORTCUT_UNKNOWN;
159 return LM_SHORTCUT_NONE;
161 #else
162 // TODO(cpu): Port to other platforms.
163 LaunchMode GetLaunchShortcutKind() {
164 return LM_LINUX_MAC_BEOS;
166 #endif
168 // Log in a histogram the frequency of launching by the different methods. See
169 // LaunchMode enum for the actual values of the buckets.
170 void RecordLaunchModeHistogram(LaunchMode mode) {
171 int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
172 UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
175 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
176 for (size_t i = 0; i < urls.size(); ++i) {
177 StartupTab tab;
178 tab.is_pinned = false;
179 tab.url = urls[i];
180 tabs->push_back(tab);
184 // Return true if the command line option --app-id is used. Set
185 // |out_extension| to the app to open, and |out_launch_container|
186 // to the type of window into which the app should be open.
187 bool GetAppLaunchContainer(
188 Profile* profile,
189 const std::string& app_id,
190 const Extension** out_extension,
191 extensions::LaunchContainer* out_launch_container) {
193 const Extension* extension = extensions::ExtensionRegistry::Get(
194 profile)->enabled_extensions().GetByID(app_id);
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 (!extensions::util::IsNewBookmarkAppsEnabled() &&
209 !extensions::HasPreferredLaunchContainer(
210 extensions::ExtensionPrefs::Get(profile), extension)) {
211 launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
214 *out_extension = extension;
215 *out_launch_container = launch_container;
216 return true;
219 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
220 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_APP,
221 app_type);
224 void RecordAppLaunches(Profile* profile,
225 const std::vector<GURL>& cmd_line_urls,
226 const StartupTabs& autolaunch_tabs) {
227 const extensions::ExtensionSet& extensions =
228 extensions::ExtensionRegistry::Get(profile)->enabled_extensions();
229 for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
230 const extensions::Extension* extension =
231 extensions.GetAppByURL(cmd_line_urls.at(i));
232 if (extension) {
233 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_CMD_LINE_URL,
234 extension->GetType());
237 for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
238 const extensions::Extension* extension =
239 extensions.GetAppByURL(autolaunch_tabs.at(i).url);
240 if (extension) {
241 extensions::RecordAppLaunchType(extension_misc::APP_LAUNCH_AUTOLAUNCH,
242 extension->GetType());
247 class WebContentsCloseObserver : public content::NotificationObserver {
248 public:
249 WebContentsCloseObserver() : contents_(NULL) {}
250 ~WebContentsCloseObserver() override {}
252 void SetContents(content::WebContents* contents) {
253 DCHECK(!contents_);
254 contents_ = contents;
256 registrar_.Add(this,
257 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
258 content::Source<content::WebContents>(contents_));
261 content::WebContents* contents() { return contents_; }
263 private:
264 // content::NotificationObserver overrides:
265 void Observe(int type,
266 const content::NotificationSource& source,
267 const content::NotificationDetails& details) override {
268 DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
269 contents_ = NULL;
272 content::WebContents* contents_;
273 content::NotificationRegistrar registrar_;
275 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
278 // TODO(koz): Consolidate this function and remove the special casing.
279 const Extension* GetPlatformApp(Profile* profile,
280 const std::string& extension_id) {
281 const Extension* extension =
282 extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
283 extension_id, extensions::ExtensionRegistry::EVERYTHING);
284 return extension && extension->is_platform_app() ? extension : NULL;
287 } // namespace
289 namespace internals {
291 GURL GetWelcomePageURL() {
292 std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
293 return GURL(welcome_url);
296 } // namespace internals
298 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
299 const base::FilePath& cur_dir,
300 const base::CommandLine& command_line,
301 chrome::startup::IsFirstRun is_first_run)
302 : cur_dir_(cur_dir),
303 command_line_(command_line),
304 profile_(NULL),
305 browser_creator_(NULL),
306 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN),
307 welcome_run_type_(WelcomeRunType::NONE) {
310 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
311 const base::FilePath& cur_dir,
312 const base::CommandLine& command_line,
313 StartupBrowserCreator* browser_creator,
314 chrome::startup::IsFirstRun is_first_run)
315 : cur_dir_(cur_dir),
316 command_line_(command_line),
317 profile_(NULL),
318 browser_creator_(browser_creator),
319 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN),
320 welcome_run_type_(WelcomeRunType::NONE) {
323 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
326 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
327 const std::vector<GURL>& urls_to_open,
328 bool process_startup,
329 chrome::HostDesktopType desktop_type) {
330 DCHECK(profile);
331 profile_ = profile;
333 if (command_line_.HasSwitch(switches::kDnsLogDetails))
334 chrome_browser_net::EnablePredictorDetailedLog(true);
336 if (AppListService::HandleLaunchCommandLine(command_line_, profile))
337 return true;
339 if (command_line_.HasSwitch(switches::kAppId)) {
340 std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
341 const Extension* extension = GetPlatformApp(profile, app_id);
342 // If |app_id| is a disabled or terminated platform app we handle it
343 // specially here, otherwise it will be handled below.
344 if (extension) {
345 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
346 AppLaunchParams params(profile, extension,
347 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW,
348 extensions::SOURCE_COMMAND_LINE);
349 params.command_line = command_line_;
350 params.current_directory = cur_dir_;
351 // If we are being launched from the command line, default to native
352 // desktop.
353 params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
354 OpenApplicationWithReenablePrompt(params);
355 return true;
359 // Open the required browser windows and tabs. First, see if
360 // we're being run as an application window. If so, the user
361 // opened an app shortcut. Don't restore tabs or open initial
362 // URLs in that case. The user should see the window as an app,
363 // not as chrome.
364 // Special case is when app switches are passed but we do want to restore
365 // session. In that case open app window + focus it after session is restored.
366 content::WebContents* app_contents = NULL;
367 if (OpenApplicationWindow(profile, &app_contents)) {
368 RecordLaunchModeHistogram(LM_AS_WEBAPP);
369 } else {
370 RecordLaunchModeHistogram(urls_to_open.empty() ?
371 LM_TO_BE_DECIDED : LM_WITH_URLS);
373 ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
375 if (command_line_.HasSwitch(switches::kInstallChromeApp)) {
376 install_chrome_app::InstallChromeApp(
377 command_line_.GetSwitchValueASCII(switches::kInstallChromeApp));
380 // If this is an app launch, but we didn't open an app window, it may
381 // be an app tab.
382 OpenApplicationTab(profile);
384 #if defined(OS_MACOSX)
385 if (process_startup) {
386 // Check whether the auto-update system needs to be promoted from user
387 // to system.
388 KeystoneInfoBar::PromotionInfoBar(profile);
390 #endif
393 // In kiosk mode, we want to always be fullscreen, so switch to that now.
394 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
395 base::CommandLine::ForCurrentProcess()->HasSwitch(
396 switches::kStartFullscreen)) {
397 // It's possible for there to be no browser window, e.g. if someone
398 // specified a non-sensical combination of options
399 // ("--kiosk --no_startup_window"); do nothing in that case.
400 Browser* browser = BrowserList::GetInstance(desktop_type)->GetLastActive();
401 if (browser)
402 chrome::ToggleFullscreenMode(browser);
405 #if defined(OS_WIN)
406 if (process_startup)
407 ShellIntegration::MigrateChromiumShortcuts();
408 #endif // defined(OS_WIN)
410 return true;
413 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
414 std::string* app_id) {
415 if (command_line_.HasSwitch(switches::kApp)) {
416 if (app_url)
417 *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
418 return true;
420 if (command_line_.HasSwitch(switches::kAppId)) {
421 if (app_id)
422 *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
423 return true;
425 return false;
428 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
429 std::string app_id;
430 // App shortcuts to URLs always open in an app window. Because this
431 // function will open an app that should be in a tab, there is no need
432 // to look at the app URL. OpenApplicationWindow() will open app url
433 // shortcuts.
434 if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
435 return false;
437 extensions::LaunchContainer launch_container;
438 const Extension* extension;
439 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
440 return false;
442 // If the user doesn't want to open a tab, fail.
443 if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
444 return false;
446 RecordCmdLineAppHistogram(extension->GetType());
448 WebContents* app_tab = OpenApplication(
449 AppLaunchParams(profile, extension, extensions::LAUNCH_CONTAINER_TAB,
450 NEW_FOREGROUND_TAB, extensions::SOURCE_COMMAND_LINE));
451 return (app_tab != NULL);
454 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
455 Profile* profile,
456 content::WebContents** out_app_contents) {
457 // Set |out_app_contents| to NULL early on (just in case).
458 if (out_app_contents)
459 *out_app_contents = NULL;
461 std::string url_string, app_id;
462 if (!IsAppLaunch(&url_string, &app_id))
463 return false;
465 // This can fail if the app_id is invalid. It can also fail if the
466 // extension is external, and has not yet been installed.
467 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
468 // Open an URL to the gallery page of the extension id?
469 if (!app_id.empty()) {
470 extensions::LaunchContainer launch_container;
471 const Extension* extension;
472 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
473 return false;
475 // TODO(skerner): Could pass in |extension| and |launch_container|,
476 // and avoid calling GetAppLaunchContainer() both here and in
477 // OpenApplicationTab().
479 if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
480 return false;
482 RecordCmdLineAppHistogram(extension->GetType());
484 AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW,
485 extensions::SOURCE_COMMAND_LINE);
486 params.command_line = command_line_;
487 params.current_directory = cur_dir_;
488 WebContents* tab_in_app_window = OpenApplication(params);
490 if (out_app_contents)
491 *out_app_contents = tab_in_app_window;
493 // Platform apps fire off a launch event which may or may not open a window.
494 return (tab_in_app_window != NULL || CanLaunchViaEvent(extension));
497 if (url_string.empty())
498 return false;
500 #if defined(OS_WIN) // Fix up Windows shortcuts.
501 base::ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
502 #endif
503 GURL url(url_string);
505 // Restrict allowed URLs for --app switch.
506 if (!url.is_empty() && url.is_valid()) {
507 ChildProcessSecurityPolicy* policy =
508 ChildProcessSecurityPolicy::GetInstance();
509 if (policy->IsWebSafeScheme(url.scheme()) ||
510 url.SchemeIs(url::kFileScheme)) {
511 const extensions::Extension* extension =
512 extensions::ExtensionRegistry::Get(profile)
513 ->enabled_extensions().GetAppByURL(url);
514 if (extension) {
515 RecordCmdLineAppHistogram(extension->GetType());
516 } else {
517 extensions::RecordAppLaunchType(
518 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
519 extensions::Manifest::TYPE_HOSTED_APP);
522 WebContents* app_tab = OpenAppShortcutWindow(profile, url);
524 if (out_app_contents)
525 *out_app_contents = app_tab;
527 return (app_tab != NULL);
530 return false;
533 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
534 bool process_startup,
535 const std::vector<GURL>& urls_to_open,
536 chrome::HostDesktopType desktop_type) {
537 // If we're starting up in "background mode" (no open browser window) then
538 // don't open any browser windows, unless kAutoLaunchAtStartup is also
539 // specified.
540 if (process_startup &&
541 command_line_.HasSwitch(switches::kNoStartupWindow) &&
542 !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
543 return;
546 // Determine whether or not this launch must include the welcome page.
547 InitializeWelcomeRunType(urls_to_open);
549 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
550 #if defined(OS_WIN)
551 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
552 // See if there are apps for this profile that should be launched on startup
553 // due to a switch from Metro mode.
554 app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
556 #endif
558 if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
559 // ProcessStartupURLs processed the urls, nothing else to do.
560 return;
563 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
564 chrome::startup::IS_PROCESS_STARTUP :
565 chrome::startup::IS_NOT_PROCESS_STARTUP;
566 if (!process_startup) {
567 // Even if we're not starting a new process, this may conceptually be
568 // "startup" for the user and so should be handled in a similar way. Eg.,
569 // Chrome may have been running in the background due to an app with a
570 // background page being installed, or running with only an app window
571 // displayed.
572 SessionService* service =
573 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
574 if (service && service->ShouldNewWindowStartSession()) {
575 // Restore the last session if any, optionally including the welcome page
576 // if desired.
577 if (!HasPendingUncleanExit(profile_)) {
578 std::vector<GURL> adjusted_urls(urls_to_open);
579 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB) {
580 adjusted_urls.insert(adjusted_urls.begin(),
581 internals::GetWelcomePageURL());
583 if (service->RestoreIfNecessary(adjusted_urls))
584 return;
587 // Open user-specified URLs like pinned tabs and startup tabs.
588 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
589 if (browser) {
590 AddInfoBarsIfNecessary(browser, is_process_startup);
591 return;
596 // Session startup didn't occur, open the urls.
597 Browser* browser = NULL;
598 std::vector<GURL> adjusted_urls = urls_to_open;
599 if (adjusted_urls.empty()) {
600 AddStartupURLs(&adjusted_urls);
601 } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
602 // Always open a list of urls in a window on the native desktop.
603 browser = chrome::FindTabbedBrowser(profile_, false,
604 chrome::HOST_DESKTOP_TYPE_NATIVE);
606 // This will launch a browser; prevent session restore.
607 StartupBrowserCreator::in_synchronous_profile_launch_ = true;
608 browser =
609 OpenURLsInBrowser(browser, process_startup, adjusted_urls, desktop_type);
610 StartupBrowserCreator::in_synchronous_profile_launch_ = false;
611 AddInfoBarsIfNecessary(browser, is_process_startup);
614 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
615 const std::vector<GURL>& urls_to_open,
616 chrome::HostDesktopType desktop_type) {
617 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
618 SessionStartupPref pref =
619 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
620 if (pref.type == SessionStartupPref::LAST)
621 VLOG(1) << "Pref: last";
622 else if (pref.type == SessionStartupPref::URLS)
623 VLOG(1) << "Pref: urls";
624 else if (pref.type == SessionStartupPref::DEFAULT)
625 VLOG(1) << "Pref: default";
627 apps::AppRestoreService* restore_service =
628 apps::AppRestoreServiceFactory::GetForProfile(profile_);
629 // NULL in incognito mode.
630 if (restore_service) {
631 restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
632 StartupBrowserCreator::WasRestarted()));
635 if (pref.type == SessionStartupPref::LAST) {
636 if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
637 !command_line_.HasSwitch(switches::kRestoreLastSession)) {
638 // The last session crashed. It's possible automatically loading the
639 // page will trigger another crash, locking the user out of chrome.
640 // To avoid this, don't restore on startup but instead show the crashed
641 // infobar.
642 VLOG(1) << "Unclean exit; not processing";
643 return false;
646 uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
647 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
648 base::CommandLine::ForCurrentProcess()->HasSwitch(
649 switches::kCreateBrowserOnStartupForTests)) {
650 restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
653 #if defined(OS_MACOSX)
654 // On Mac, when restoring a session with no windows, suppress the creation
655 // of a new window in the case where the system is launching Chrome via a
656 // login item or Lion's resume feature.
657 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
658 restore_behavior = restore_behavior &
659 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
661 #endif
663 // Optionally include the welcome page.
664 std::vector<GURL> adjusted_urls(urls_to_open);
665 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB) {
666 adjusted_urls.insert(adjusted_urls.begin(),
667 internals::GetWelcomePageURL());
670 // The startup code only executes for browsers launched in desktop mode.
671 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
672 Browser* browser = SessionRestore::RestoreSession(
673 profile_, NULL, desktop_type, restore_behavior, adjusted_urls);
675 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
676 return true;
679 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
680 if (!browser)
681 return false;
683 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
685 // Session restore may occur if the startup preference is "last" or if the
686 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
687 // to start deleting leftover data.
688 if (pref.type != SessionStartupPref::LAST &&
689 !HasPendingUncleanExit(profile_)) {
690 content::BrowserContext::GetDefaultStoragePartition(profile_)->
691 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
694 return true;
697 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
698 const std::vector<GURL>& urls_to_open,
699 chrome::HostDesktopType desktop_type) {
700 SessionStartupPref pref =
701 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
702 StartupTabs tabs;
703 // Pinned tabs should not be displayed when chrome is launched in incognito
704 // mode. Also, no pages should be opened automatically if the session
705 // crashed. Otherwise it might trigger another crash, locking the user out of
706 // chrome. The crash infobar is shown in this case.
707 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
708 profile_->GetPrefs()) &&
709 !HasPendingUncleanExit(profile_)) {
710 tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
713 RecordAppLaunches(profile_, urls_to_open, tabs);
715 if (!urls_to_open.empty()) {
716 // If urls were specified on the command line, use them.
717 UrlsToTabs(urls_to_open, &tabs);
718 } else if (pref.type == SessionStartupPref::DEFAULT ||
719 (is_first_run_ &&
720 browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
721 std::vector<GURL> urls;
722 AddStartupURLs(&urls);
723 UrlsToTabs(urls, &tabs);
724 } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
725 !HasPendingUncleanExit(profile_)) {
726 // Optionally include the welcome page first.
727 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB)
728 UrlsToTabs(std::vector<GURL>(1, internals::GetWelcomePageURL()), &tabs);
729 // Only use the set of urls specified in preferences if nothing was
730 // specified on the command line. Filter out any urls that are to be
731 // restored by virtue of having been previously pinned.
732 AddUniqueURLs(pref.urls, &tabs);
733 } else if (pref.type == SessionStartupPref::HOMEPAGE) {
734 // If 'homepage' selected, either by the user or by a policy, we should
735 // have migrated them to another value.
736 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
739 if (tabs.empty())
740 return NULL;
742 Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
743 return browser;
746 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
747 StartupTabs* tabs) {
748 size_t num_existing_tabs = tabs->size();
749 for (size_t i = 0; i < urls.size(); ++i) {
750 bool in_tabs = false;
751 for (size_t j = 0; j < num_existing_tabs; ++j) {
752 if (urls[i] == (*tabs)[j].url) {
753 in_tabs = true;
754 break;
757 if (!in_tabs) {
758 StartupTab tab;
759 tab.is_pinned = false;
760 tab.url = urls[i];
761 tabs->push_back(tab);
766 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
767 Browser* browser,
768 bool process_startup,
769 const std::vector<GURL>& urls,
770 chrome::HostDesktopType desktop_type) {
771 StartupTabs tabs;
772 UrlsToTabs(urls, &tabs);
773 return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
776 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
777 Browser* browser,
778 bool process_startup,
779 const StartupTabs& tabs,
780 chrome::HostDesktopType desktop_type) {
781 DCHECK(!tabs.empty());
783 // If we don't yet have a profile, try to use the one we're given from
784 // |browser|. While we may not end up actually using |browser| (since it
785 // could be a popup window), we can at least use the profile.
786 if (!profile_ && browser)
787 profile_ = browser->profile();
789 if (!browser || !browser->is_type_tabbed())
790 browser = new Browser(Browser::CreateParams(profile_, desktop_type));
792 bool first_tab = true;
793 ProtocolHandlerRegistry* registry = profile_ ?
794 ProtocolHandlerRegistryFactory::GetForBrowserContext(profile_) : NULL;
795 for (size_t i = 0; i < tabs.size(); ++i) {
796 // We skip URLs that we'd have to launch an external protocol handler for.
797 // This avoids us getting into an infinite loop asking ourselves to open
798 // a URL, should the handler be (incorrectly) configured to be us. Anyone
799 // asking us to open such a URL should really ask the handler directly.
800 bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
801 (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
802 if (!process_startup && !handled_by_chrome)
803 continue;
805 int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
806 TabStripModel::ADD_NONE;
807 add_types |= TabStripModel::ADD_FORCE_INDEX;
808 if (tabs[i].is_pinned)
809 add_types |= TabStripModel::ADD_PINNED;
811 chrome::NavigateParams params(browser, tabs[i].url,
812 ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
813 params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
814 params.tabstrip_add_types = add_types;
816 #if defined(ENABLE_RLZ) && !defined(OS_IOS)
817 if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
818 params.extra_headers = rlz::RLZTracker::GetAccessPointHttpHeader(
819 rlz::RLZTracker::ChromeHomePage());
821 #endif // defined(ENABLE_RLZ) && !defined(OS_IOS)
823 chrome::Navigate(&params);
825 first_tab = false;
827 if (!browser->tab_strip_model()->GetActiveWebContents()) {
828 // TODO: this is a work around for 110909. Figure out why it's needed.
829 if (!browser->tab_strip_model()->count())
830 chrome::AddTabAt(browser, GURL(), -1, true);
831 else
832 browser->tab_strip_model()->ActivateTabAt(0, false);
835 // The default behavior is to show the window, as expressed by the default
836 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
837 // to true ahead of this place, it means another task must have been spawned
838 // to take care of that.
839 if (!browser_creator_ || browser_creator_->show_main_browser_window())
840 browser->window()->Show();
842 return browser;
845 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
846 Browser* browser,
847 chrome::startup::IsProcessStartup is_process_startup) {
848 if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
849 return;
851 if (HasPendingUncleanExit(browser->profile()) &&
852 !browser->window()->ShowSessionCrashedBubble()) {
853 SessionCrashedInfoBarDelegate::Create(browser);
856 // The below info bars are only added to the first profile which is launched.
857 // Other profiles might be restoring the browsing sessions asynchronously,
858 // so we cannot add the info bars to the focused tabs here.
859 if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP &&
860 !command_line_.HasSwitch(switches::kTestType)) {
861 chrome::ShowBadFlagsPrompt(browser);
862 GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
863 browser->tab_strip_model()->GetActiveWebContents()));
864 ObsoleteSystemInfoBarDelegate::Create(InfoBarService::FromWebContents(
865 browser->tab_strip_model()->GetActiveWebContents()));
867 #if !defined(OS_CHROMEOS)
868 if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
869 // Generally, the default browser prompt should not be shown on first
870 // run. However, when the set-as-default dialog has been suppressed, we
871 // need to allow it.
872 if ((!is_first_run_ ||
873 (browser_creator_ &&
874 browser_creator_->is_default_browser_dialog_suppressed())) &&
875 !chrome::ShowAutolaunchPrompt(browser)) {
876 chrome::ShowDefaultBrowserPrompt(profile_,
877 browser->host_desktop_type());
880 #endif
884 void StartupBrowserCreatorImpl::AddStartupURLs(
885 std::vector<GURL>* startup_urls) const {
886 // TODO(atwilson): Simplify the logic that decides which tabs to open on
887 // start-up and make it more consistent. http://crbug.com/248883
889 // If we have urls specified by the first run master preferences use them
890 // and nothing else.
891 if (browser_creator_ && startup_urls->empty()) {
892 if (!browser_creator_->first_run_tabs_.empty()) {
893 std::vector<GURL>::iterator it =
894 browser_creator_->first_run_tabs_.begin();
895 while (it != browser_creator_->first_run_tabs_.end()) {
896 // Replace magic names for the actual urls.
897 if (it->host() == "new_tab_page") {
898 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
899 } else if (it->host() == "welcome_page") {
900 startup_urls->push_back(internals::GetWelcomePageURL());
901 } else {
902 startup_urls->push_back(*it);
904 ++it;
906 browser_creator_->first_run_tabs_.clear();
910 // Otherwise open at least the new tab page (and optionally the welcome page
911 // at the front or back as indicated by welcome_run_type_), or the set of URLs
912 // specified on the command line.
913 if (startup_urls->empty()) {
914 if (welcome_run_type_ == WelcomeRunType::FIRST_TAB)
915 startup_urls->push_back(internals::GetWelcomePageURL());
916 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
917 if (welcome_run_type_ == WelcomeRunType::FIRST_RUN_LAST_TAB)
918 startup_urls->push_back(internals::GetWelcomePageURL());
921 if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
922 signin::DidShowPromoAtStartup(profile_);
924 const GURL sync_promo_url = signin::GetPromoURL(
925 signin_metrics::SOURCE_START_PAGE, false);
927 // No need to add if the sync promo is already in the startup list.
928 bool add_promo = true;
929 for (std::vector<GURL>::const_iterator it = startup_urls->begin();
930 it != startup_urls->end(); ++it) {
931 if (*it == sync_promo_url) {
932 add_promo = false;
933 break;
937 if (add_promo) {
938 // If the first URL is the NTP, replace it with the sync promo. This
939 // behavior is desired because completing or skipping the sync promo
940 // causes a redirect to the NTP.
941 if (!startup_urls->empty() &&
942 startup_urls->at(0) == GURL(chrome::kChromeUINewTabURL))
943 startup_urls->at(0) = sync_promo_url;
944 else
945 startup_urls->insert(startup_urls->begin(), sync_promo_url);
950 // For first-run, the type will be FIRST_RUN_LAST for all systems except for
951 // Windows 10+, where it will be FIRST_RUN_FIRST. For non-first run, the type
952 // will be NONE for all systems except for Windows 10+, where it will be
953 // ANY_RUN_FIRST if this is the first somewhat normal launch since an OS
954 // upgrade.
955 void StartupBrowserCreatorImpl::InitializeWelcomeRunType(
956 const std::vector<GURL>& urls_to_open) {
957 DCHECK_EQ(static_cast<int>(WelcomeRunType::NONE),
958 static_cast<int>(welcome_run_type_));
959 #if defined(OS_WIN)
960 // Do not welcome if there are any URLs to open.
961 if (!urls_to_open.empty())
962 return;
964 base::win::OSInfo* const os_info = base::win::OSInfo::GetInstance();
965 const base::win::OSInfo::VersionNumber v(os_info->version_number());
966 const std::string this_version(base::StringPrintf("%d.%d", v.major, v.minor));
967 PrefService* const local_state = g_browser_process->local_state();
969 // Always welcome on first run.
970 if (first_run::ShouldShowWelcomePage()) {
971 // First tab for Win10+, last tab otherwise.
972 welcome_run_type_ = os_info->version() >= base::win::VERSION_WIN10
973 ? WelcomeRunType::FIRST_TAB
974 : WelcomeRunType::FIRST_RUN_LAST_TAB;
975 } else {
976 // Otherwise, do not welcome pre-Win10.
977 if (base::win::GetVersion() < base::win::VERSION_WIN10)
978 return;
980 // Do not welcome if launching into incognito.
981 if (IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
982 profile_->GetPrefs())) {
983 return;
986 // Do not welcome if there is no local state (tests).
987 if (!local_state)
988 return;
990 // Do not welcome if disabled by policy or master_preferences.
991 if (!local_state->GetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled))
992 return;
994 // Do not welcome if already shown for this OS version.
995 if (local_state->GetString(prefs::kLastWelcomedOSVersion) == this_version)
996 return;
998 // Do not welcome if offline.
999 if (net::NetworkChangeNotifier::IsOffline())
1000 return;
1002 // Do not welcome if Chrome was the default browser at startup.
1003 if (g_browser_process->CachedDefaultWebClientState() ==
1004 ShellIntegration::IS_DEFAULT) {
1005 return;
1008 // Show the welcome page in the first tab.
1009 welcome_run_type_ = WelcomeRunType::FIRST_TAB;
1012 // Remember that the welcome page was shown for this OS version.
1013 local_state->SetString(prefs::kLastWelcomedOSVersion, this_version);
1014 #else // OS_WIN
1015 // Show the welcome page as the last tab only on first-run.
1016 if (first_run::ShouldShowWelcomePage())
1017 welcome_run_type_ = WelcomeRunType::FIRST_RUN_LAST_TAB;
1018 #endif // !OS_WIN