Add unit test for the Settings API Bubble.
[chromium-blink-merge.git] / chrome / browser / ui / startup / startup_browser_creator_impl.cc
blobbcf713a43d013c42c269b80facd32949508059e2
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/auto_launch_trial.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
31 #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
32 #include "chrome/browser/defaults.h"
33 #include "chrome/browser/extensions/extension_creator.h"
34 #include "chrome/browser/extensions/extension_service.h"
35 #include "chrome/browser/extensions/launch_util.h"
36 #include "chrome/browser/extensions/pack_extension_job.h"
37 #include "chrome/browser/first_run/first_run.h"
38 #include "chrome/browser/google/google_util.h"
39 #include "chrome/browser/infobars/infobar_service.h"
40 #include "chrome/browser/net/predictor.h"
41 #include "chrome/browser/notifications/desktop_notification_service.h"
42 #include "chrome/browser/performance_monitor/startup_timer.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/rlz/rlz.h"
48 #include "chrome/browser/sessions/session_restore.h"
49 #include "chrome/browser/sessions/session_service.h"
50 #include "chrome/browser/sessions/session_service_factory.h"
51 #include "chrome/browser/shell_integration.h"
52 #include "chrome/browser/signin/signin_promo.h"
53 #include "chrome/browser/ui/app_list/app_list_service.h"
54 #include "chrome/browser/ui/browser_commands.h"
55 #include "chrome/browser/ui/browser_finder.h"
56 #include "chrome/browser/ui/browser_list.h"
57 #include "chrome/browser/ui/browser_navigator.h"
58 #include "chrome/browser/ui/browser_tabrestore.h"
59 #include "chrome/browser/ui/browser_tabstrip.h"
60 #include "chrome/browser/ui/browser_window.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/browser/ui/webui/ntp/core_app_launcher_handler.h"
73 #include "chrome/common/chrome_constants.h"
74 #include "chrome/common/chrome_paths.h"
75 #include "chrome/common/chrome_result_codes.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/chrome_version_info.h"
78 #include "chrome/common/extensions/extension_constants.h"
79 #include "chrome/common/net/url_fixer_upper.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/installer/util/browser_distribution.h"
83 #include "content/public/browser/child_process_security_policy.h"
84 #include "content/public/browser/dom_storage_context.h"
85 #include "content/public/browser/notification_observer.h"
86 #include "content/public/browser/notification_registrar.h"
87 #include "content/public/browser/storage_partition.h"
88 #include "content/public/browser/web_contents.h"
89 #include "content/public/browser/web_contents_view.h"
90 #include "extensions/browser/extension_prefs.h"
91 #include "extensions/browser/extension_registry.h"
92 #include "extensions/browser/extension_system.h"
93 #include "extensions/common/constants.h"
94 #include "grit/locale_settings.h"
95 #include "ui/base/l10n/l10n_util.h"
96 #include "ui/base/resource/resource_bundle.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(TOOLKIT_GTK)
104 #include "chrome/browser/ui/gtk/gtk_util.h"
105 #endif
107 #if defined(OS_WIN)
108 #include "base/win/windows_version.h"
109 #include "chrome/browser/apps/app_launch_for_metro_restart_win.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::ASCIIToWide(appdata_path)) != std::wstring::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 ExtensionService* extensions_service = profile->GetExtensionService();
194 const Extension* extension =
195 extensions_service->GetExtensionById(app_id, false);
196 // The extension with id |app_id| may have been uninstalled.
197 if (!extension)
198 return false;
200 // Don't launch platform apps in incognito mode.
201 if (profile->IsOffTheRecord() && extension->is_platform_app())
202 return false;
204 // Look at preferences to find the right launch container. If no
205 // preference is set, launch as a window.
206 extensions::LaunchContainer launch_container = extensions::GetLaunchContainer(
207 extensions::ExtensionPrefs::Get(profile), extension);
209 if (!CommandLine::ForCurrentProcess()->HasSwitch(
210 switches::kEnableStreamlinedHostedApps) &&
211 !extensions::HasPreferredLaunchContainer(
212 extensions::ExtensionPrefs::Get(profile), extension)) {
213 launch_container = extensions::LAUNCH_CONTAINER_WINDOW;
216 *out_extension = extension;
217 *out_launch_container = launch_container;
218 return true;
221 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
222 CoreAppLauncherHandler::RecordAppLaunchType(
223 extension_misc::APP_LAUNCH_CMD_LINE_APP,
224 app_type);
227 void RecordAppLaunches(Profile* profile,
228 const std::vector<GURL>& cmd_line_urls,
229 StartupTabs& autolaunch_tabs) {
230 ExtensionService* extension_service = profile->GetExtensionService();
231 DCHECK(extension_service);
232 for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
233 const extensions::Extension* extension =
234 extension_service->GetInstalledApp(cmd_line_urls.at(i));
235 if (extension) {
236 CoreAppLauncherHandler::RecordAppLaunchType(
237 extension_misc::APP_LAUNCH_CMD_LINE_URL,
238 extension->GetType());
241 for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
242 const extensions::Extension* extension =
243 extension_service->GetInstalledApp(autolaunch_tabs.at(i).url);
244 if (extension) {
245 CoreAppLauncherHandler::RecordAppLaunchType(
246 extension_misc::APP_LAUNCH_AUTOLAUNCH,
247 extension->GetType());
252 bool IsNewTabURL(Profile* profile, const GURL& url) {
253 GURL ntp_url(chrome::kChromeUINewTabURL);
254 return url == ntp_url ||
255 (url.is_empty() && profile->GetHomePage() == ntp_url);
258 class WebContentsCloseObserver : public content::NotificationObserver {
259 public:
260 WebContentsCloseObserver() : contents_(NULL) {}
261 virtual ~WebContentsCloseObserver() {}
263 void SetContents(content::WebContents* contents) {
264 DCHECK(!contents_);
265 contents_ = contents;
267 registrar_.Add(this,
268 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
269 content::Source<content::WebContents>(contents_));
272 content::WebContents* contents() { return contents_; }
274 private:
275 // content::NotificationObserver overrides:
276 virtual void Observe(int type,
277 const content::NotificationSource& source,
278 const content::NotificationDetails& details) OVERRIDE {
279 DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
280 contents_ = NULL;
283 content::WebContents* contents_;
284 content::NotificationRegistrar registrar_;
286 DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
289 // TODO(koz): Consolidate this function and remove the special casing.
290 const Extension* GetPlatformApp(Profile* profile,
291 const std::string& extension_id) {
292 const Extension* extension =
293 extensions::ExtensionRegistry::Get(profile)->GetExtensionById(
294 extension_id, extensions::ExtensionRegistry::EVERYTHING);
295 return extension && extension->is_platform_app() ? extension : NULL;
298 } // namespace
300 namespace internals {
302 GURL GetWelcomePageURL() {
303 std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
304 return GURL(welcome_url);
307 } // namespace internals
309 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
310 const base::FilePath& cur_dir,
311 const CommandLine& command_line,
312 chrome::startup::IsFirstRun is_first_run)
313 : cur_dir_(cur_dir),
314 command_line_(command_line),
315 profile_(NULL),
316 browser_creator_(NULL),
317 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
320 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
321 const base::FilePath& cur_dir,
322 const CommandLine& command_line,
323 StartupBrowserCreator* browser_creator,
324 chrome::startup::IsFirstRun is_first_run)
325 : cur_dir_(cur_dir),
326 command_line_(command_line),
327 profile_(NULL),
328 browser_creator_(browser_creator),
329 is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
332 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
335 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
336 const std::vector<GURL>& urls_to_open,
337 bool process_startup,
338 chrome::HostDesktopType desktop_type) {
339 DCHECK(profile);
340 profile_ = profile;
342 if (command_line_.HasSwitch(switches::kDnsLogDetails))
343 chrome_browser_net::EnablePredictorDetailedLog(true);
344 if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
345 profile->GetNetworkPredictor()) {
346 profile->GetNetworkPredictor()->EnablePredictor(false);
349 AppListService::InitAll(profile);
350 if (command_line_.HasSwitch(switches::kAppId)) {
351 std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
352 const Extension* extension = GetPlatformApp(profile, app_id);
353 // If |app_id| is a disabled or terminated platform app we handle it
354 // specially here, otherwise it will be handled below.
355 if (extension) {
356 RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
357 AppLaunchParams params(profile, extension,
358 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW);
359 params.command_line = command_line_;
360 params.current_directory = cur_dir_;
361 // If we are being launched from the command line, default to native
362 // desktop.
363 params.desktop_type = chrome::HOST_DESKTOP_TYPE_NATIVE;
364 OpenApplicationWithReenablePrompt(params);
365 return true;
367 } else if (command_line_.HasSwitch(switches::kShowAppList)) {
368 // This switch is used for shortcuts on the native desktop.
369 AppListService::RecordShowTimings(command_line_);
370 AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
371 ShowForProfile(profile);
372 return true;
375 // Open the required browser windows and tabs. First, see if
376 // we're being run as an application window. If so, the user
377 // opened an app shortcut. Don't restore tabs or open initial
378 // URLs in that case. The user should see the window as an app,
379 // not as chrome.
380 // Special case is when app switches are passed but we do want to restore
381 // session. In that case open app window + focus it after session is restored.
382 content::WebContents* app_contents = NULL;
383 if (OpenApplicationWindow(profile, &app_contents)) {
384 RecordLaunchModeHistogram(LM_AS_WEBAPP);
385 } else {
386 RecordLaunchModeHistogram(urls_to_open.empty() ?
387 LM_TO_BE_DECIDED : LM_WITH_URLS);
389 ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
391 // If this is an app launch, but we didn't open an app window, it may
392 // be an app tab.
393 OpenApplicationTab(profile);
395 #if defined(OS_MACOSX)
396 if (process_startup) {
397 // Check whether the auto-update system needs to be promoted from user
398 // to system.
399 KeystoneInfoBar::PromotionInfoBar(profile);
401 #endif
404 #if defined(OS_WIN)
405 if (process_startup)
406 ShellIntegration::MigrateChromiumShortcuts();
407 #endif // defined(OS_WIN)
409 return true;
412 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
413 std::string* app_id) {
414 if (command_line_.HasSwitch(switches::kApp)) {
415 if (app_url)
416 *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
417 return true;
419 if (command_line_.HasSwitch(switches::kAppId)) {
420 if (app_id)
421 *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
422 return true;
424 return false;
427 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
428 std::string app_id;
429 // App shortcuts to URLs always open in an app window. Because this
430 // function will open an app that should be in a tab, there is no need
431 // to look at the app URL. OpenApplicationWindow() will open app url
432 // shortcuts.
433 if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
434 return false;
436 extensions::LaunchContainer launch_container;
437 const Extension* extension;
438 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
439 return false;
441 // If the user doesn't want to open a tab, fail.
442 if (launch_container != extensions::LAUNCH_CONTAINER_TAB)
443 return false;
445 RecordCmdLineAppHistogram(extension->GetType());
447 WebContents* app_tab = OpenApplication(AppLaunchParams(
448 profile, extension, extensions::LAUNCH_CONTAINER_TAB,
449 NEW_FOREGROUND_TAB));
450 return (app_tab != NULL);
453 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
454 Profile* profile,
455 content::WebContents** out_app_contents) {
456 // Set |out_app_contents| to NULL early on (just in case).
457 if (out_app_contents)
458 *out_app_contents = NULL;
460 std::string url_string, app_id;
461 if (!IsAppLaunch(&url_string, &app_id))
462 return false;
464 // This can fail if the app_id is invalid. It can also fail if the
465 // extension is external, and has not yet been installed.
466 // TODO(skerner): Do something reasonable here. Pop up a warning panel?
467 // Open an URL to the gallery page of the extension id?
468 if (!app_id.empty()) {
469 extensions::LaunchContainer launch_container;
470 const Extension* extension;
471 if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
472 return false;
474 // TODO(skerner): Could pass in |extension| and |launch_container|,
475 // and avoid calling GetAppLaunchContainer() both here and in
476 // OpenApplicationTab().
478 if (launch_container == extensions::LAUNCH_CONTAINER_TAB)
479 return false;
481 RecordCmdLineAppHistogram(extension->GetType());
483 AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW);
484 params.command_line = command_line_;
485 params.current_directory = cur_dir_;
486 WebContents* tab_in_app_window = OpenApplication(params);
488 if (out_app_contents)
489 *out_app_contents = tab_in_app_window;
491 // Platform apps fire off a launch event which may or may not open a window.
492 return (tab_in_app_window != NULL || extension->is_platform_app());
495 if (url_string.empty())
496 return false;
498 #if defined(OS_WIN) // Fix up Windows shortcuts.
499 ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
500 #endif
501 GURL url(url_string);
503 // Restrict allowed URLs for --app switch.
504 if (!url.is_empty() && url.is_valid()) {
505 ChildProcessSecurityPolicy* policy =
506 ChildProcessSecurityPolicy::GetInstance();
507 if (policy->IsWebSafeScheme(url.scheme()) ||
508 url.SchemeIs(content::kFileScheme)) {
509 const extensions::Extension* extension =
510 profile->GetExtensionService()->GetInstalledApp(url);
511 if (extension) {
512 RecordCmdLineAppHistogram(extension->GetType());
513 } else {
514 CoreAppLauncherHandler::RecordAppLaunchType(
515 extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
516 extensions::Manifest::TYPE_HOSTED_APP);
519 WebContents* app_tab = OpenAppShortcutWindow(profile, url);
521 if (out_app_contents)
522 *out_app_contents = app_tab;
524 return (app_tab != NULL);
527 return false;
530 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
531 bool process_startup,
532 const std::vector<GURL>& urls_to_open,
533 chrome::HostDesktopType desktop_type) {
534 // If we're starting up in "background mode" (no open browser window) then
535 // don't open any browser windows, unless kAutoLaunchAtStartup is also
536 // specified.
537 if (process_startup &&
538 command_line_.HasSwitch(switches::kNoStartupWindow) &&
539 !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
540 return;
543 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
544 #if defined(OS_WIN)
545 if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
546 // See if there are apps for this profile that should be launched on startup
547 // due to a switch from Metro mode.
548 app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
550 #endif
552 if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
553 // ProcessStartupURLs processed the urls, nothing else to do.
554 return;
557 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
558 chrome::startup::IS_PROCESS_STARTUP :
559 chrome::startup::IS_NOT_PROCESS_STARTUP;
560 if (!process_startup) {
561 // Even if we're not starting a new process, this may conceptually be
562 // "startup" for the user and so should be handled in a similar way. Eg.,
563 // Chrome may have been running in the background due to an app with a
564 // background page being installed, or running with only an app window
565 // displayed.
566 SessionService* service =
567 SessionServiceFactory::GetForProfileForSessionRestore(profile_);
568 if (service && service->ShouldNewWindowStartSession()) {
569 // Restore the last session if any.
570 if (!HasPendingUncleanExit(profile_) &&
571 service->RestoreIfNecessary(urls_to_open)) {
572 return;
574 // Open user-specified URLs like pinned tabs and startup tabs.
575 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
576 if (browser) {
577 AddInfoBarsIfNecessary(browser, is_process_startup);
578 return;
583 // Session startup didn't occur, open the urls.
584 Browser* browser = NULL;
585 std::vector<GURL> adjust_urls = urls_to_open;
586 if (adjust_urls.empty()) {
587 AddStartupURLs(&adjust_urls);
588 if (StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
589 profile_, adjust_urls))
590 return;
591 } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
592 // Always open a list of urls in a window on the native desktop.
593 browser = chrome::FindTabbedBrowser(profile_, false,
594 chrome::HOST_DESKTOP_TYPE_NATIVE);
596 // This will launch a browser; prevent session restore.
597 StartupBrowserCreator::in_synchronous_profile_launch_ = true;
598 browser = OpenURLsInBrowser(browser, process_startup, adjust_urls,
599 desktop_type);
600 StartupBrowserCreator::in_synchronous_profile_launch_ = false;
601 AddInfoBarsIfNecessary(browser, is_process_startup);
604 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
605 const std::vector<GURL>& urls_to_open,
606 chrome::HostDesktopType desktop_type) {
607 VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
608 SessionStartupPref pref =
609 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
610 if (pref.type == SessionStartupPref::LAST)
611 VLOG(1) << "Pref: last";
612 else if (pref.type == SessionStartupPref::URLS)
613 VLOG(1) << "Pref: urls";
614 else if (pref.type == SessionStartupPref::DEFAULT)
615 VLOG(1) << "Pref: default";
617 apps::AppRestoreService* restore_service =
618 apps::AppRestoreServiceFactory::GetForProfile(profile_);
619 // NULL in incognito mode.
620 if (restore_service) {
621 restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
622 StartupBrowserCreator::WasRestarted()));
625 if (pref.type == SessionStartupPref::LAST) {
626 if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
627 !command_line_.HasSwitch(switches::kRestoreLastSession)) {
628 // The last session crashed. It's possible automatically loading the
629 // page will trigger another crash, locking the user out of chrome.
630 // To avoid this, don't restore on startup but instead show the crashed
631 // infobar.
632 VLOG(1) << "Unclean exit; not processing";
633 return false;
636 uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
637 if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
638 CommandLine::ForCurrentProcess()->HasSwitch(
639 switches::kCreateBrowserOnStartupForTests)) {
640 restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
643 #if defined(OS_MACOSX)
644 // On Mac, when restoring a session with no windows, suppress the creation
645 // of a new window in the case where the system is launching Chrome via a
646 // login item or Lion's resume feature.
647 if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
648 restore_behavior = restore_behavior &
649 ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
651 #endif
653 // Pause the StartupTimer. Since the restore here is synchronous, we can
654 // keep these two metrics (browser startup time and session restore time)
655 // separate.
656 performance_monitor::StartupTimer::PauseTimer();
658 // The startup code only executes for browsers launched in desktop mode.
659 // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
660 Browser* browser = SessionRestore::RestoreSession(
661 profile_, NULL, desktop_type, restore_behavior,
662 urls_to_open);
664 performance_monitor::StartupTimer::UnpauseTimer();
666 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
667 return true;
670 Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
671 if (!browser)
672 return false;
674 AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
676 // Session restore may occur if the startup preference is "last" or if the
677 // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
678 // to start deleting leftover data.
679 if (pref.type != SessionStartupPref::LAST &&
680 !HasPendingUncleanExit(profile_)) {
681 content::BrowserContext::GetDefaultStoragePartition(profile_)->
682 GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
685 return true;
688 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
689 const std::vector<GURL>& urls_to_open,
690 chrome::HostDesktopType desktop_type) {
691 SessionStartupPref pref =
692 StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
693 StartupTabs tabs;
694 // Pinned tabs should not be displayed when chrome is launched in incognito
695 // mode. Also, no pages should be opened automatically if the session
696 // crashed. Otherwise it might trigger another crash, locking the user out of
697 // chrome. The crash infobar is shown in this case.
698 if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
699 profile_->GetPrefs()) &&
700 !HasPendingUncleanExit(profile_)) {
701 tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
704 RecordAppLaunches(profile_, urls_to_open, tabs);
706 if (!urls_to_open.empty()) {
707 // If urls were specified on the command line, use them.
708 UrlsToTabs(urls_to_open, &tabs);
709 } else if (pref.type == SessionStartupPref::DEFAULT ||
710 (is_first_run_ &&
711 browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
712 std::vector<GURL> urls;
713 AddStartupURLs(&urls);
714 UrlsToTabs(urls, &tabs);
715 } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
716 !HasPendingUncleanExit(profile_)) {
717 // Only use the set of urls specified in preferences if nothing was
718 // specified on the command line. Filter out any urls that are to be
719 // restored by virtue of having been previously pinned.
720 AddUniqueURLs(pref.urls, &tabs);
721 } else if (pref.type == SessionStartupPref::HOMEPAGE) {
722 // If 'homepage' selected, either by the user or by a policy, we should
723 // have migrated them to another value.
724 NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
727 if (tabs.empty())
728 return NULL;
730 Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
731 return browser;
734 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
735 StartupTabs* tabs) {
736 size_t num_existing_tabs = tabs->size();
737 for (size_t i = 0; i < urls.size(); ++i) {
738 bool in_tabs = false;
739 for (size_t j = 0; j < num_existing_tabs; ++j) {
740 if (urls[i] == (*tabs)[j].url) {
741 in_tabs = true;
742 break;
745 if (!in_tabs) {
746 StartupTab tab;
747 tab.is_pinned = false;
748 tab.url = urls[i];
749 tabs->push_back(tab);
754 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
755 Browser* browser,
756 bool process_startup,
757 const std::vector<GURL>& urls,
758 chrome::HostDesktopType desktop_type) {
759 StartupTabs tabs;
760 UrlsToTabs(urls, &tabs);
761 return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
764 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
765 Browser* browser,
766 bool process_startup,
767 const StartupTabs& tabs,
768 chrome::HostDesktopType desktop_type) {
769 DCHECK(!tabs.empty());
771 // If we don't yet have a profile, try to use the one we're given from
772 // |browser|. While we may not end up actually using |browser| (since it
773 // could be a popup window), we can at least use the profile.
774 if (!profile_ && browser)
775 profile_ = browser->profile();
777 if (!browser || !browser->is_type_tabbed()) {
778 browser = new Browser(Browser::CreateParams(profile_, desktop_type));
779 } else {
780 #if defined(TOOLKIT_GTK)
781 // Setting the time of the last action on the window here allows us to steal
782 // focus, which is what the user wants when opening a new tab in an existing
783 // browser window.
784 gtk_util::SetWMLastUserActionTime(browser->window()->GetNativeWindow());
785 #endif
788 bool first_tab = true;
789 ProtocolHandlerRegistry* registry = profile_ ?
790 ProtocolHandlerRegistryFactory::GetForProfile(profile_) : NULL;
791 for (size_t i = 0; i < tabs.size(); ++i) {
792 // We skip URLs that we'd have to launch an external protocol handler for.
793 // This avoids us getting into an infinite loop asking ourselves to open
794 // a URL, should the handler be (incorrectly) configured to be us. Anyone
795 // asking us to open such a URL should really ask the handler directly.
796 bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
797 (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
798 if (!process_startup && !handled_by_chrome)
799 continue;
801 int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
802 TabStripModel::ADD_NONE;
803 add_types |= TabStripModel::ADD_FORCE_INDEX;
804 if (tabs[i].is_pinned)
805 add_types |= TabStripModel::ADD_PINNED;
807 chrome::NavigateParams params(browser, tabs[i].url,
808 content::PAGE_TRANSITION_AUTO_TOPLEVEL);
809 params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
810 params.tabstrip_add_types = add_types;
811 params.extension_app_id = tabs[i].app_id;
813 #if defined(ENABLE_RLZ)
814 if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
815 params.extra_headers = RLZTracker::GetAccessPointHttpHeader(
816 RLZTracker::CHROME_HOME_PAGE);
818 #endif
820 chrome::Navigate(&params);
822 first_tab = false;
824 if (!browser->tab_strip_model()->GetActiveWebContents()) {
825 // TODO: this is a work around for 110909. Figure out why it's needed.
826 if (!browser->tab_strip_model()->count())
827 chrome::AddTabAt(browser, GURL(), -1, true);
828 else
829 browser->tab_strip_model()->ActivateTabAt(0, false);
832 // The default behavior is to show the window, as expressed by the default
833 // value of StartupBrowserCreated::show_main_browser_window_. If this was set
834 // to true ahead of this place, it means another task must have been spawned
835 // to take care of that.
836 if (!browser_creator_ || browser_creator_->show_main_browser_window())
837 browser->window()->Show();
839 // In kiosk mode, we want to always be fullscreen, so switch to that now.
840 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
841 CommandLine::ForCurrentProcess()->HasSwitch(switches::kStartFullscreen))
842 chrome::ToggleFullscreenMode(browser);
844 return browser;
847 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
848 Browser* browser,
849 chrome::startup::IsProcessStartup is_process_startup) {
850 if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
851 return;
853 if (HasPendingUncleanExit(browser->profile()))
854 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 the welcome page, if this
911 // is the first time the browser is being started), or the set of URLs
912 // specified on the command line.
913 if (startup_urls->empty()) {
914 startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
915 if (first_run::ShouldShowWelcomePage())
916 startup_urls->push_back(internals::GetWelcomePageURL());
919 if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
920 signin::DidShowPromoAtStartup(profile_);
922 const GURL sync_promo_url = signin::GetPromoURL(signin::SOURCE_START_PAGE,
923 false);
925 // No need to add if the sync promo is already in the startup list.
926 bool add_promo = true;
927 for (std::vector<GURL>::const_iterator it = startup_urls->begin();
928 it != startup_urls->end(); ++it) {
929 if (*it == sync_promo_url) {
930 add_promo = false;
931 break;
935 if (add_promo) {
936 // If the first URL is the NTP, replace it with the sync promo. This
937 // behavior is desired because completing or skipping the sync promo
938 // causes a redirect to the NTP.
939 if (!startup_urls->empty() && IsNewTabURL(profile_, startup_urls->at(0)))
940 startup_urls->at(0) = sync_promo_url;
941 else
942 startup_urls->insert(startup_urls->begin(), sync_promo_url);
947 #if !defined(OS_WIN)
948 // static
949 bool StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
950 Profile* profile,
951 const std::vector<GURL>& startup_urls) {
952 return false;
954 #endif