Infobar material design refresh: layout
[chromium-blink-merge.git] / chrome / browser / ui / startup / startup_browser_creator.cc
blobf7fac34905f789c96ce28d0107dca525986da7ce
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.h"
7 #include <algorithm> // For max().
8 #include <set>
10 #include "apps/app_load_service.h"
11 #include "apps/switches.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/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/lazy_instance.h"
20 #include "base/logging.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/metrics/statistics_recorder.h"
24 #include "base/prefs/pref_registry_simple.h"
25 #include "base/prefs/pref_service.h"
26 #include "base/profiler/scoped_profile.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_tokenizer.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/threading/thread_restrictions.h"
32 #include "base/trace_event/trace_event.h"
33 #include "chrome/browser/app_mode/app_mode_utils.h"
34 #include "chrome/browser/auto_launch_trial.h"
35 #include "chrome/browser/browser_process.h"
36 #include "chrome/browser/chrome_notification_types.h"
37 #include "chrome/browser/custom_handlers/protocol_handler_registry.h"
38 #include "chrome/browser/extensions/startup_helper.h"
39 #include "chrome/browser/extensions/unpacked_installer.h"
40 #include "chrome/browser/first_run/first_run.h"
41 #include "chrome/browser/net/predictor.h"
42 #include "chrome/browser/prefs/incognito_mode_prefs.h"
43 #include "chrome/browser/prefs/session_startup_pref.h"
44 #include "chrome/browser/profiles/profile.h"
45 #include "chrome/browser/profiles/profile_manager.h"
46 #include "chrome/browser/profiles/profiles_state.h"
47 #include "chrome/browser/search_engines/template_url_service_factory.h"
48 #include "chrome/browser/ui/app_list/app_list_service.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_dialogs.h"
51 #include "chrome/browser/ui/browser_finder.h"
52 #include "chrome/browser/ui/browser_window.h"
53 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
54 #include "chrome/browser/ui/user_manager.h"
55 #include "chrome/common/chrome_constants.h"
56 #include "chrome/common/chrome_paths.h"
57 #include "chrome/common/chrome_result_codes.h"
58 #include "chrome/common/chrome_switches.h"
59 #include "chrome/common/pref_names.h"
60 #include "chrome/common/url_constants.h"
61 #include "chrome/installer/util/browser_distribution.h"
62 #include "components/google/core/browser/google_util.h"
63 #include "components/search_engines/util.h"
64 #include "components/signin/core/common/profile_management_switches.h"
65 #include "components/url_formatter/url_fixer.h"
66 #include "content/public/browser/browser_thread.h"
67 #include "content/public/browser/child_process_security_policy.h"
68 #include "content/public/browser/navigation_controller.h"
69 #include "content/public/common/content_switches.h"
70 #include "extensions/common/switches.h"
71 #include "net/base/port_util.h"
73 #if defined(USE_ASH)
74 #include "ash/shell.h"
75 #endif
77 #if defined(OS_CHROMEOS)
78 #include "chrome/browser/chromeos/app_mode/app_launch_utils.h"
79 #include "chrome/browser/chromeos/login/demo_mode/demo_app_launcher.h"
80 #include "chrome/browser/chromeos/profiles/profile_helper.h"
81 #include "chrome/browser/lifetime/application_lifetime.h"
82 #include "chromeos/chromeos_switches.h"
83 #include "components/user_manager/user_manager.h"
84 #endif
86 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX)
87 #include "ui/events/devices/x11/touch_factory_x11.h"
88 #endif
90 #if defined(OS_MACOSX)
91 #include "chrome/browser/web_applications/web_app_mac.h"
92 #endif
94 #if defined(OS_WIN)
95 #include "chrome/browser/metrics/jumplist_metrics_win.h"
96 #endif
98 #if defined(ENABLE_PRINT_PREVIEW)
99 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
100 #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
101 #include "chrome/browser/printing/print_dialog_cloud.h"
102 #endif
104 using content::BrowserThread;
105 using content::ChildProcessSecurityPolicy;
107 namespace {
109 // Keeps track on which profiles have been launched.
110 class ProfileLaunchObserver : public content::NotificationObserver {
111 public:
112 ProfileLaunchObserver()
113 : profile_to_activate_(NULL),
114 activated_profile_(false) {
115 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
116 content::NotificationService::AllSources());
117 registrar_.Add(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY,
118 content::NotificationService::AllSources());
120 ~ProfileLaunchObserver() override {}
122 void Observe(int type,
123 const content::NotificationSource& source,
124 const content::NotificationDetails& details) override {
125 switch (type) {
126 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
127 Profile* profile = content::Source<Profile>(source).ptr();
128 launched_profiles_.erase(profile);
129 opened_profiles_.erase(profile);
130 if (profile == profile_to_activate_)
131 profile_to_activate_ = NULL;
132 // If this profile was the last launched one without an opened window,
133 // then we may be ready to activate |profile_to_activate_|.
134 MaybeActivateProfile();
135 break;
137 case chrome::NOTIFICATION_BROWSER_WINDOW_READY: {
138 Browser* browser = content::Source<Browser>(source).ptr();
139 DCHECK(browser);
140 opened_profiles_.insert(browser->profile());
141 MaybeActivateProfile();
142 break;
144 default:
145 NOTREACHED();
149 bool HasBeenLaunched(const Profile* profile) const {
150 return launched_profiles_.find(profile) != launched_profiles_.end();
153 void AddLaunched(Profile* profile) {
154 launched_profiles_.insert(profile);
155 // Since the startup code only executes for browsers launched in
156 // desktop mode, i.e., HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
157 if (chrome::FindBrowserWithProfile(profile,
158 chrome::HOST_DESKTOP_TYPE_NATIVE)) {
159 // A browser may get opened before we get initialized (e.g., in tests),
160 // so we never see the NOTIFICATION_BROWSER_WINDOW_READY for it.
161 opened_profiles_.insert(profile);
165 void Clear() {
166 launched_profiles_.clear();
167 opened_profiles_.clear();
170 bool activated_profile() { return activated_profile_; }
172 void set_profile_to_activate(Profile* profile) {
173 profile_to_activate_ = profile;
174 MaybeActivateProfile();
177 private:
178 void MaybeActivateProfile() {
179 if (!profile_to_activate_)
180 return;
181 // Check that browsers have been opened for all the launched profiles.
182 // Note that browsers opened for profiles that were not added as launched
183 // profiles are simply ignored.
184 std::set<const Profile*>::const_iterator i = launched_profiles_.begin();
185 for (; i != launched_profiles_.end(); ++i) {
186 if (opened_profiles_.find(*i) == opened_profiles_.end())
187 return;
189 // Asynchronous post to give a chance to the last window to completely
190 // open and activate before trying to activate |profile_to_activate_|.
191 BrowserThread::PostTask(
192 BrowserThread::UI, FROM_HERE,
193 base::Bind(&ProfileLaunchObserver::ActivateProfile,
194 base::Unretained(this)));
195 // Avoid posting more than once before ActivateProfile gets called.
196 registrar_.Remove(this, chrome::NOTIFICATION_BROWSER_WINDOW_READY,
197 content::NotificationService::AllSources());
198 registrar_.Remove(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
199 content::NotificationService::AllSources());
202 void ActivateProfile() {
203 // We need to test again, in case the profile got deleted in the mean time.
204 if (profile_to_activate_) {
205 Browser* browser = chrome::FindBrowserWithProfile(
206 profile_to_activate_, chrome::HOST_DESKTOP_TYPE_NATIVE);
207 // |profile| may never get launched, e.g., if it only had
208 // incognito Windows and one of them was used to exit Chrome.
209 // So it won't have a browser in that case.
210 if (browser)
211 browser->window()->Activate();
212 // No need try to activate this profile again.
213 profile_to_activate_ = NULL;
215 // Assign true here, even if no browser was actually activated, so that
216 // the test can stop waiting, and fail gracefully when needed.
217 activated_profile_ = true;
220 // These are the profiles that get launched by
221 // StartupBrowserCreator::LaunchBrowser.
222 std::set<const Profile*> launched_profiles_;
223 // These are the profiles for which at least one browser window has been
224 // opened. This is needed to know when it is safe to activate
225 // |profile_to_activate_|, otherwise, new browser windows being opened will
226 // be activated on top of it.
227 std::set<const Profile*> opened_profiles_;
228 content::NotificationRegistrar registrar_;
229 // This is NULL until the profile to activate has been chosen. This value,
230 // should only be set once all profiles have been launched, otherwise,
231 // activation may not happen after the launch of newer profiles.
232 Profile* profile_to_activate_;
233 // Set once we attempted to activate a profile. We only get one shot at this.
234 bool activated_profile_;
236 DISALLOW_COPY_AND_ASSIGN(ProfileLaunchObserver);
239 base::LazyInstance<ProfileLaunchObserver> profile_launch_observer =
240 LAZY_INSTANCE_INITIALIZER;
242 // Dumps the current set of the browser process's histograms to |output_file|.
243 // The file is overwritten if it exists. This function should only be called in
244 // the blocking pool.
245 void DumpBrowserHistograms(const base::FilePath& output_file) {
246 base::ThreadRestrictions::AssertIOAllowed();
248 std::string output_string(base::StatisticsRecorder::ToJSON(std::string()));
249 base::WriteFile(output_file, output_string.data(),
250 static_cast<int>(output_string.size()));
253 } // namespace
255 StartupBrowserCreator::StartupBrowserCreator()
256 : is_default_browser_dialog_suppressed_(false),
257 show_main_browser_window_(true) {
260 StartupBrowserCreator::~StartupBrowserCreator() {}
262 // static
263 bool StartupBrowserCreator::was_restarted_read_ = false;
265 // static
266 bool StartupBrowserCreator::in_synchronous_profile_launch_ = false;
268 void StartupBrowserCreator::AddFirstRunTab(const GURL& url) {
269 first_run_tabs_.push_back(url);
272 bool StartupBrowserCreator::Start(const base::CommandLine& cmd_line,
273 const base::FilePath& cur_dir,
274 Profile* last_used_profile,
275 const Profiles& last_opened_profiles) {
276 TRACE_EVENT0("startup", "StartupBrowserCreator::Start");
277 TRACK_SCOPED_REGION("Startup", "StartupBrowserCreator::Start");
278 SCOPED_UMA_HISTOGRAM_TIMER("Startup.StartupBrowserCreator_Start");
279 return ProcessCmdLineImpl(cmd_line, cur_dir, true, last_used_profile,
280 last_opened_profiles, this);
283 // static
284 bool StartupBrowserCreator::InSynchronousProfileLaunch() {
285 return in_synchronous_profile_launch_;
288 bool StartupBrowserCreator::LaunchBrowser(
289 const base::CommandLine& command_line,
290 Profile* profile,
291 const base::FilePath& cur_dir,
292 chrome::startup::IsProcessStartup process_startup,
293 chrome::startup::IsFirstRun is_first_run) {
294 DCHECK(profile);
295 in_synchronous_profile_launch_ =
296 process_startup == chrome::startup::IS_PROCESS_STARTUP;
298 // ChromeOS does a direct browser launch from UserSessionManager, so this is
299 // the earliest place we can enable the log.
300 if (command_line.HasSwitch(switches::kDnsLogDetails))
301 chrome_browser_net::EnablePredictorDetailedLog(true);
303 // Continue with the incognito profile from here on if Incognito mode
304 // is forced.
305 if (IncognitoModePrefs::ShouldLaunchIncognito(command_line,
306 profile->GetPrefs())) {
307 profile = profile->GetOffTheRecordProfile();
308 } else if (command_line.HasSwitch(switches::kIncognito)) {
309 LOG(WARNING) << "Incognito mode disabled by policy, launching a normal "
310 << "browser session.";
313 // Note: This check should have been done in ProcessCmdLineImpl()
314 // before calling this function. However chromeos/login/login_utils.cc
315 // calls this function directly (see comments there) so it has to be checked
316 // again.
317 const bool silent_launch = command_line.HasSwitch(switches::kSilentLaunch);
319 if (!silent_launch) {
320 StartupBrowserCreatorImpl lwp(cur_dir, command_line, this, is_first_run);
321 const std::vector<GURL> urls_to_launch =
322 GetURLsFromCommandLine(command_line, cur_dir, profile);
323 chrome::HostDesktopType host_desktop_type =
324 chrome::HOST_DESKTOP_TYPE_NATIVE;
326 #if defined(USE_ASH) && !defined(OS_CHROMEOS)
327 // We want to maintain only one type of instance for now, either ASH
328 // or desktop.
329 // TODO(shrikant): Remove this code once we decide on running both desktop
330 // and ASH instances side by side.
331 if (ash::Shell::HasInstance())
332 host_desktop_type = chrome::HOST_DESKTOP_TYPE_ASH;
333 #endif
335 const bool launched = lwp.Launch(profile, urls_to_launch,
336 in_synchronous_profile_launch_,
337 host_desktop_type);
338 in_synchronous_profile_launch_ = false;
339 if (!launched) {
340 LOG(ERROR) << "launch error";
341 return false;
343 } else {
344 in_synchronous_profile_launch_ = false;
347 profile_launch_observer.Get().AddLaunched(profile);
349 #if defined(OS_CHROMEOS)
350 chromeos::ProfileHelper::Get()->ProfileStartup(profile, process_startup);
351 #endif
352 return true;
355 // static
356 bool StartupBrowserCreator::WasRestarted() {
357 // Stores the value of the preference kWasRestarted had when it was read.
358 static bool was_restarted = false;
360 if (!was_restarted_read_) {
361 PrefService* pref_service = g_browser_process->local_state();
362 was_restarted = pref_service->GetBoolean(prefs::kWasRestarted);
363 pref_service->SetBoolean(prefs::kWasRestarted, false);
364 was_restarted_read_ = true;
366 return was_restarted;
369 // static
370 SessionStartupPref StartupBrowserCreator::GetSessionStartupPref(
371 const base::CommandLine& command_line,
372 Profile* profile) {
373 DCHECK(profile);
374 PrefService* prefs = profile->GetPrefs();
375 SessionStartupPref pref = SessionStartupPref::GetStartupPref(prefs);
377 // IsChromeFirstRun() looks for a sentinel file to determine whether the user
378 // is starting Chrome for the first time. On Chrome OS, the sentinel is stored
379 // in a location shared by all users and the check is meaningless. Query the
380 // UserManager instead to determine whether the user is new.
381 #if defined(OS_CHROMEOS)
382 const bool is_first_run =
383 user_manager::UserManager::Get()->IsCurrentUserNew();
384 // On ChromeOS restarts force the user to login again. The expectation is that
385 // after a login the user gets clean state. For this reason we ignore
386 // StartupBrowserCreator::WasRestarted().
387 const bool did_restart = false;
388 #else
389 const bool is_first_run = first_run::IsChromeFirstRun();
390 const bool did_restart = StartupBrowserCreator::WasRestarted();
391 #endif
393 // The pref has an OS-dependent default value. For the first run only, this
394 // default is overridden with SessionStartupPref::DEFAULT so that first run
395 // behavior (sync promo, welcome page) is consistently invoked.
396 // This applies only if the pref is still at its default and has not been
397 // set by the user, managed prefs or policy.
398 if (is_first_run && SessionStartupPref::TypeIsDefault(prefs))
399 pref.type = SessionStartupPref::DEFAULT;
401 // The switches::kRestoreLastSession command line switch is used to restore
402 // sessions after a browser self restart (e.g. after a Chrome upgrade).
403 // However, new profiles can be created from a browser process that has this
404 // switch so do not set the session pref to SessionStartupPref::LAST for
405 // those as there is nothing to restore.
406 if ((command_line.HasSwitch(switches::kRestoreLastSession) || did_restart) &&
407 !profile->IsNewProfile()) {
408 pref.type = SessionStartupPref::LAST;
411 // A browser starting for a profile being unlocked should always restore.
412 if (!profile->IsGuestSession()) {
413 ProfileInfoCache& info_cache =
414 g_browser_process->profile_manager()->GetProfileInfoCache();
415 size_t index = info_cache.GetIndexOfProfileWithPath(profile->GetPath());
417 if (index != std::string::npos &&
418 info_cache.ProfileIsSigninRequiredAtIndex(index)) {
419 pref.type = SessionStartupPref::LAST;
423 if (pref.type == SessionStartupPref::LAST &&
424 IncognitoModePrefs::ShouldLaunchIncognito(command_line, prefs)) {
425 // We don't store session information when incognito. If the user has
426 // chosen to restore last session and launched incognito, fallback to
427 // default launch behavior.
428 pref.type = SessionStartupPref::DEFAULT;
431 return pref;
434 // static
435 void StartupBrowserCreator::ClearLaunchedProfilesForTesting() {
436 profile_launch_observer.Get().Clear();
439 // static
440 void StartupBrowserCreator::RegisterLocalStatePrefs(
441 PrefRegistrySimple* registry) {
442 #if defined(OS_WIN)
443 registry->RegisterStringPref(prefs::kLastWelcomedOSVersion, std::string());
444 registry->RegisterBooleanPref(prefs::kWelcomePageOnOSUpgradeEnabled, true);
445 #endif
448 // static
449 std::vector<GURL> StartupBrowserCreator::GetURLsFromCommandLine(
450 const base::CommandLine& command_line,
451 const base::FilePath& cur_dir,
452 Profile* profile) {
453 std::vector<GURL> urls;
455 const base::CommandLine::StringVector& params = command_line.GetArgs();
456 for (size_t i = 0; i < params.size(); ++i) {
457 base::FilePath param = base::FilePath(params[i]);
458 // Handle Vista way of searching - "? <search-term>"
459 if ((param.value().size() > 2) && (param.value()[0] == '?') &&
460 (param.value()[1] == ' ')) {
461 GURL url(GetDefaultSearchURLForSearchTerms(
462 TemplateURLServiceFactory::GetForProfile(profile),
463 param.LossyDisplayName().substr(2)));
464 if (url.is_valid()) {
465 urls.push_back(url);
466 continue;
470 // Otherwise, fall through to treating it as a URL.
472 // This will create a file URL or a regular URL.
473 // This call can (in rare circumstances) block the UI thread.
474 // Allow it until this bug is fixed.
475 // http://code.google.com/p/chromium/issues/detail?id=60641
476 GURL url = GURL(param.MaybeAsASCII());
477 // http://crbug.com/371030: Only use URLFixerUpper if we don't have a valid
478 // URL, otherwise we will look in the current directory for a file named
479 // 'about' if the browser was started with a about:foo argument.
480 if (!url.is_valid()) {
481 base::ThreadRestrictions::ScopedAllowIO allow_io;
482 url = url_formatter::FixupRelativeFile(cur_dir, param);
484 // Exclude dangerous schemes.
485 if (url.is_valid()) {
486 ChildProcessSecurityPolicy* policy =
487 ChildProcessSecurityPolicy::GetInstance();
488 if (policy->IsWebSafeScheme(url.scheme()) ||
489 url.SchemeIs(url::kFileScheme) ||
490 #if defined(OS_CHROMEOS)
491 // In ChromeOS, allow any settings page to be specified on the command
492 // line. See ExistingUserController::OnLoginSuccess.
493 (url.spec().find(chrome::kChromeUISettingsURL) == 0) ||
494 #else
495 ((url.spec().find(std::string(chrome::kChromeUISettingsURL) +
496 chrome::kResetProfileSettingsSubPage) == 0)) ||
497 #endif
498 (url.spec().compare(url::kAboutBlankURL) == 0)) {
499 urls.push_back(url);
503 return urls;
506 // static
507 bool StartupBrowserCreator::ProcessCmdLineImpl(
508 const base::CommandLine& command_line,
509 const base::FilePath& cur_dir,
510 bool process_startup,
511 Profile* last_used_profile,
512 const Profiles& last_opened_profiles,
513 StartupBrowserCreator* browser_creator) {
514 TRACE_EVENT0("startup", "StartupBrowserCreator::ProcessCmdLineImpl");
516 DCHECK(last_used_profile);
517 if (process_startup) {
518 if (command_line.HasSwitch(switches::kDisablePromptOnRepost))
519 content::NavigationController::DisablePromptOnRepost();
522 bool silent_launch = false;
524 #if defined(ENABLE_PRINT_PREVIEW)
525 // If we are just displaying a print dialog we shouldn't open browser
526 // windows.
527 if (command_line.HasSwitch(switches::kCloudPrintFile) &&
528 print_dialog_cloud::CreatePrintDialogFromCommandLine(last_used_profile,
529 command_line)) {
530 silent_launch = true;
532 #endif // defined(ENABLE_PRINT_PREVIEW)
534 if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) {
535 std::string allowed_ports =
536 command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts);
537 net::SetExplicitlyAllowedPorts(allowed_ports);
540 if (command_line.HasSwitch(switches::kValidateCrx)) {
541 if (!process_startup) {
542 LOG(ERROR) << "chrome is already running; you must close all running "
543 << "instances before running with the --"
544 << switches::kValidateCrx << " flag";
545 return false;
547 extensions::StartupHelper helper;
548 std::string message;
549 std::string error;
550 if (helper.ValidateCrx(command_line, &error))
551 message = std::string("ValidateCrx Success");
552 else
553 message = std::string("ValidateCrx Failure: ") + error;
554 printf("%s\n", message.c_str());
555 return false;
558 #if defined(OS_CHROMEOS)
560 // The browser will be launched after the user logs in.
561 if (command_line.HasSwitch(chromeos::switches::kLoginManager))
562 silent_launch = true;
564 if (chrome::IsRunningInAppMode() &&
565 command_line.HasSwitch(switches::kAppId)) {
566 chromeos::LaunchAppOrDie(
567 last_used_profile,
568 command_line.GetSwitchValueASCII(switches::kAppId));
570 // Skip browser launch since app mode launches its app window.
571 silent_launch = true;
574 // If we are a demo app session and we crashed, there is no safe recovery
575 // possible. We should instead cleanly exit and go back to the OOBE screen,
576 // where we will launch again after the timeout has expired.
577 if (chromeos::DemoAppLauncher::IsDemoAppSession(
578 command_line.GetSwitchValueASCII(chromeos::switches::kLoginUser))) {
579 chrome::AttemptUserExit();
580 return false;
582 #endif // OS_CHROMEOS
584 #if defined(TOOLKIT_VIEWS) && defined(USE_X11)
585 ui::TouchFactory::SetTouchDeviceListFromCommandLine();
586 #endif
588 #if defined(OS_MACOSX)
589 if (web_app::MaybeRebuildShortcut(command_line))
590 return true;
591 #endif
593 if (!process_startup &&
594 command_line.HasSwitch(switches::kDumpBrowserHistograms)) {
595 // Only handle --dump-browser-histograms from a rendezvous. In this case, do
596 // not open a new browser window even if no output file was given.
597 base::FilePath output_file(
598 command_line.GetSwitchValuePath(switches::kDumpBrowserHistograms));
599 if (!output_file.empty()) {
600 BrowserThread::PostBlockingPoolTask(
601 FROM_HERE,
602 base::Bind(&DumpBrowserHistograms, output_file));
604 silent_launch = true;
607 // If --no-startup-window is specified and Chrome is already running then do
608 // not open a new window.
609 if (!process_startup && command_line.HasSwitch(switches::kNoStartupWindow))
610 silent_launch = true;
612 // If we don't want to launch a new browser window or tab we are done here.
613 if (silent_launch)
614 return true;
616 if (command_line.HasSwitch(extensions::switches::kLoadApps) &&
617 !IncognitoModePrefs::ShouldLaunchIncognito(
618 command_line, last_used_profile->GetPrefs())) {
619 if (!ProcessLoadApps(command_line, cur_dir, last_used_profile))
620 return false;
622 // Return early here to avoid opening a browser window.
623 // The exception is when there are no browser windows, since we don't want
624 // chrome to shut down.
625 // TODO(jackhou): Do this properly once keep-alive is handled by the
626 // background page of apps. Tracked at http://crbug.com/175381
627 if (chrome::GetTotalBrowserCountForProfile(last_used_profile) != 0)
628 return true;
631 // Check for --load-and-launch-app.
632 if (command_line.HasSwitch(apps::kLoadAndLaunchApp) &&
633 !IncognitoModePrefs::ShouldLaunchIncognito(
634 command_line, last_used_profile->GetPrefs())) {
635 base::CommandLine::StringType path =
636 command_line.GetSwitchValueNative(apps::kLoadAndLaunchApp);
638 if (!apps::AppLoadService::Get(last_used_profile)->LoadAndLaunch(
639 base::FilePath(path), command_line, cur_dir)) {
640 return false;
643 // Return early here since we don't want to open a browser window.
644 // The exception is when there are no browser windows, since we don't want
645 // chrome to shut down.
646 // TODO(jackhou): Do this properly once keep-alive is handled by the
647 // background page of apps. Tracked at http://crbug.com/175381
648 if (chrome::GetTotalBrowserCountForProfile(last_used_profile) != 0)
649 return true;
652 #if defined(OS_WIN)
653 // Log whether this process was a result of an action in the Windows Jumplist.
654 if (command_line.HasSwitch(switches::kWinJumplistAction)) {
655 jumplist::LogJumplistActionFromSwitchValue(
656 command_line.GetSwitchValueASCII(switches::kWinJumplistAction));
658 #endif
660 chrome::startup::IsProcessStartup is_process_startup = process_startup ?
661 chrome::startup::IS_PROCESS_STARTUP :
662 chrome::startup::IS_NOT_PROCESS_STARTUP;
663 chrome::startup::IsFirstRun is_first_run = first_run::IsChromeFirstRun() ?
664 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
665 // |last_opened_profiles| will be empty in the following circumstances:
666 // - This is the first launch. |last_used_profile| is the initial profile.
667 // - The user exited the browser by closing all windows for all
668 // profiles. |last_used_profile| is the profile which owned the last open
669 // window.
670 // - Only incognito windows were open when the browser exited.
671 // |last_used_profile| is the last used incognito profile. Restoring it will
672 // create a browser window for the corresponding original profile.
673 if (last_opened_profiles.empty()) {
674 // If the last used profile is locked or was a guest, show the user manager.
675 if (switches::IsNewAvatarMenu()) {
676 ProfileInfoCache& profile_info =
677 g_browser_process->profile_manager()->GetProfileInfoCache();
678 size_t profile_index = profile_info.GetIndexOfProfileWithPath(
679 last_used_profile->GetPath());
680 bool signin_required = profile_index != std::string::npos &&
681 profile_info.ProfileIsSigninRequiredAtIndex(profile_index);
683 // Guest, system or locked profiles cannot be re-opened on startup. The
684 // only exception is if there's already a Guest window open in a separate
685 // process (for example, launching a new browser after clicking on a
686 // downloaded file in Guest mode).
687 bool guest_or_system = last_used_profile->IsGuestSession() ||
688 last_used_profile->IsSystemProfile();
689 bool has_guest_browsers = guest_or_system &&
690 chrome::GetTotalBrowserCountForProfile(
691 last_used_profile->GetOffTheRecordProfile()) > 0;
692 if (signin_required || (guest_or_system && !has_guest_browsers)) {
693 profiles::UserManagerProfileSelected action =
694 command_line.HasSwitch(switches::kShowAppList) ?
695 profiles::USER_MANAGER_SELECT_PROFILE_APP_LAUNCHER :
696 profiles::USER_MANAGER_SELECT_PROFILE_NO_ACTION;
697 UserManager::Show(
698 base::FilePath(), profiles::USER_MANAGER_NO_TUTORIAL, action);
699 return true;
703 Profile* profile_to_open = last_used_profile->IsGuestSession() ?
704 last_used_profile->GetOffTheRecordProfile() : last_used_profile;
706 if (!browser_creator->LaunchBrowser(command_line, profile_to_open,
707 cur_dir, is_process_startup,
708 is_first_run)) {
709 return false;
711 } else {
712 // Guest profiles should not be reopened on startup. This can happen if
713 // the last used profile was a Guest, but other profiles were also open
714 // when Chrome was closed. In this case, pick a different open profile
715 // to be the active one, since the Guest profile is never added to the list
716 // of open profiles.
717 if (switches::IsNewAvatarMenu() && last_used_profile->IsGuestSession()) {
718 DCHECK(!last_opened_profiles[0]->IsGuestSession());
719 last_used_profile = last_opened_profiles[0];
722 // Launch the last used profile with the full command line, and the other
723 // opened profiles without the URLs to launch.
724 base::CommandLine command_line_without_urls(command_line.GetProgram());
725 const base::CommandLine::SwitchMap& switches = command_line.GetSwitches();
726 for (base::CommandLine::SwitchMap::const_iterator switch_it =
727 switches.begin();
728 switch_it != switches.end(); ++switch_it) {
729 command_line_without_urls.AppendSwitchNative(switch_it->first,
730 switch_it->second);
732 // Launch the profiles in the order they became active.
733 for (Profiles::const_iterator it = last_opened_profiles.begin();
734 it != last_opened_profiles.end(); ++it) {
735 DCHECK(!(*it)->IsGuestSession());
736 // Don't launch additional profiles which would only open a new tab
737 // page. When restarting after an update, all profiles will reopen last
738 // open pages.
739 SessionStartupPref startup_pref =
740 GetSessionStartupPref(command_line, *it);
741 if (*it != last_used_profile &&
742 startup_pref.type == SessionStartupPref::DEFAULT &&
743 !HasPendingUncleanExit(*it))
744 continue;
746 if (!browser_creator->LaunchBrowser((*it == last_used_profile) ?
747 command_line : command_line_without_urls, *it, cur_dir,
748 is_process_startup, is_first_run))
749 return false;
750 // We've launched at least one browser.
751 is_process_startup = chrome::startup::IS_NOT_PROCESS_STARTUP;
753 // This must be done after all profiles have been launched so the observer
754 // knows about all profiles to wait for before activating this one.
755 profile_launch_observer.Get().set_profile_to_activate(last_used_profile);
757 return true;
760 // static
761 bool StartupBrowserCreator::ProcessLoadApps(
762 const base::CommandLine& command_line,
763 const base::FilePath& cur_dir,
764 Profile* profile) {
765 base::CommandLine::StringType path_list =
766 command_line.GetSwitchValueNative(extensions::switches::kLoadApps);
768 base::StringTokenizerT<base::CommandLine::StringType,
769 base::CommandLine::StringType::const_iterator>
770 tokenizer(path_list, FILE_PATH_LITERAL(","));
772 if (!tokenizer.GetNext())
773 return false;
775 base::FilePath app_absolute_dir =
776 base::MakeAbsoluteFilePath(base::FilePath(tokenizer.token()));
777 if (!apps::AppLoadService::Get(profile)->LoadAndLaunch(
778 app_absolute_dir, command_line, cur_dir)) {
779 return false;
782 while (tokenizer.GetNext()) {
783 app_absolute_dir =
784 base::MakeAbsoluteFilePath(base::FilePath(tokenizer.token()));
786 if (!apps::AppLoadService::Get(profile)->Load(app_absolute_dir)) {
787 return false;
791 return true;
794 // static
795 void StartupBrowserCreator::ProcessCommandLineOnProfileCreated(
796 const base::CommandLine& command_line,
797 const base::FilePath& cur_dir,
798 Profile* profile,
799 Profile::CreateStatus status) {
800 if (status != Profile::CREATE_STATUS_INITIALIZED)
801 return;
802 ProcessCmdLineImpl(command_line, cur_dir, false, profile, Profiles(), NULL);
805 // static
806 void StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
807 const base::CommandLine& command_line,
808 const base::FilePath& cur_dir,
809 const base::FilePath& profile_path) {
810 ProfileManager* profile_manager = g_browser_process->profile_manager();
811 Profile* profile = profile_manager->GetProfileByPath(profile_path);
813 // The profile isn't loaded yet and so needs to be loaded asynchronously.
814 if (!profile) {
815 profile_manager->CreateProfileAsync(profile_path,
816 base::Bind(&StartupBrowserCreator::ProcessCommandLineOnProfileCreated,
817 command_line, cur_dir), base::string16(), base::string16(),
818 std::string());
819 return;
822 ProcessCmdLineImpl(command_line, cur_dir, false, profile, Profiles(), NULL);
825 // static
826 bool StartupBrowserCreator::ActivatedProfile() {
827 return profile_launch_observer.Get().activated_profile();
830 bool HasPendingUncleanExit(Profile* profile) {
831 return profile->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
832 !profile_launch_observer.Get().HasBeenLaunched(profile);
835 base::FilePath GetStartupProfilePath(const base::FilePath& user_data_dir,
836 const base::CommandLine& command_line) {
837 if (command_line.HasSwitch(switches::kProfileDirectory)) {
838 return user_data_dir.Append(
839 command_line.GetSwitchValuePath(switches::kProfileDirectory));
842 // If we are showing the app list then chrome isn't shown so load the app
843 // list's profile rather than chrome's.
844 if (command_line.HasSwitch(switches::kShowAppList)) {
845 return AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
846 GetProfilePath(user_data_dir);
849 return g_browser_process->profile_manager()->GetLastUsedProfileDir(
850 user_data_dir);