- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / startup / startup_browser_creator_impl.cc
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.
4
5 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
6
7 #include <algorithm>
8 #include <vector>
9
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/extension_system.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_os_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 "grit/locale_settings.h"
91 #include "ui/base/l10n/l10n_util.h"
92 #include "ui/base/resource/resource_bundle.h"
93 #include "ui/gfx/rect.h"
94 #include "ui/gfx/screen.h"
95
96 #if defined(OS_MACOSX)
97 #include "base/mac/mac_util.h"
98 #include "chrome/browser/ui/cocoa/keystone_infobar_delegate.h"
99 #endif
100
101 #if defined(TOOLKIT_GTK)
102 #include "chrome/browser/ui/gtk/gtk_util.h"
103 #endif
104
105 #if defined(OS_WIN)
106 #include "base/win/windows_version.h"
107 #include "chrome/browser/apps/app_launch_for_metro_restart_win.h"
108 #endif
109
110 using content::ChildProcessSecurityPolicy;
111 using content::WebContents;
112 using extensions::Extension;
113
114 namespace {
115
116 // Utility functions ----------------------------------------------------------
117
118 enum LaunchMode {
119   LM_TO_BE_DECIDED = 0,       // Possibly direct launch or via a shortcut.
120   LM_AS_WEBAPP,               // Launched as a installed web application.
121   LM_WITH_URLS,               // Launched with urls in the cmd line.
122   LM_SHORTCUT_NONE,           // Not launched from a shortcut.
123   LM_SHORTCUT_NONAME,         // Launched from shortcut but no name available.
124   LM_SHORTCUT_UNKNOWN,        // Launched from user-defined shortcut.
125   LM_SHORTCUT_QUICKLAUNCH,    // Launched from the quick launch bar.
126   LM_SHORTCUT_DESKTOP,        // Launched from a desktop shortcut.
127   LM_SHORTCUT_TASKBAR,        // Launched from the taskbar.
128   LM_LINUX_MAC_BEOS           // Other OS buckets start here.
129 };
130
131 #if defined(OS_WIN)
132 // Undocumented flag in the startup info structure tells us what shortcut was
133 // used to launch the browser. See http://www.catch22.net/tuts/undoc01 for
134 // more information. Confirmed to work on XP, Vista and Win7.
135 LaunchMode GetLaunchShortcutKind() {
136   STARTUPINFOW si = { sizeof(si) };
137   GetStartupInfoW(&si);
138   if (si.dwFlags & 0x800) {
139     if (!si.lpTitle)
140       return LM_SHORTCUT_NONAME;
141     string16 shortcut(si.lpTitle);
142     // The windows quick launch path is not localized.
143     if (shortcut.find(L"\\Quick Launch\\") != string16::npos) {
144       if (base::win::GetVersion() >= base::win::VERSION_WIN7)
145         return LM_SHORTCUT_TASKBAR;
146       else
147         return LM_SHORTCUT_QUICKLAUNCH;
148     }
149     scoped_ptr<base::Environment> env(base::Environment::Create());
150     std::string appdata_path;
151     env->GetVar("USERPROFILE", &appdata_path);
152     if (!appdata_path.empty() &&
153         shortcut.find(ASCIIToWide(appdata_path)) != std::wstring::npos)
154       return LM_SHORTCUT_DESKTOP;
155     return LM_SHORTCUT_UNKNOWN;
156   }
157   return LM_SHORTCUT_NONE;
158 }
159 #else
160 // TODO(cpu): Port to other platforms.
161 LaunchMode GetLaunchShortcutKind() {
162   return LM_LINUX_MAC_BEOS;
163 }
164 #endif
165
166 // Log in a histogram the frequency of launching by the different methods. See
167 // LaunchMode enum for the actual values of the buckets.
168 void RecordLaunchModeHistogram(LaunchMode mode) {
169   int bucket = (mode == LM_TO_BE_DECIDED) ? GetLaunchShortcutKind() : mode;
170   UMA_HISTOGRAM_COUNTS_100("Launch.Modes", bucket);
171 }
172
173 void UrlsToTabs(const std::vector<GURL>& urls, StartupTabs* tabs) {
174   for (size_t i = 0; i < urls.size(); ++i) {
175     StartupTab tab;
176     tab.is_pinned = false;
177     tab.url = urls[i];
178     tabs->push_back(tab);
179   }
180 }
181
182 // Return true if the command line option --app-id is used.  Set
183 // |out_extension| to the app to open, and |out_launch_container|
184 // to the type of window into which the app should be open.
185 bool GetAppLaunchContainer(
186     Profile* profile,
187     const std::string& app_id,
188     const Extension** out_extension,
189     extension_misc::LaunchContainer* out_launch_container) {
190
191   ExtensionService* extensions_service = profile->GetExtensionService();
192   const Extension* extension =
193       extensions_service->GetExtensionById(app_id, false);
194
195   // The extension with id |app_id| may have been uninstalled.
196   if (!extension)
197     return false;
198
199   // Don't launch platform apps in incognito mode.
200   if (profile->IsOffTheRecord() && extension->is_platform_app())
201     return false;
202
203   // Look at preferences to find the right launch container.  If no
204   // preference is set, launch as a window.
205   extension_misc::LaunchContainer launch_container =
206       extensions_service->extension_prefs()->GetLaunchContainer(
207           extension, extensions::ExtensionPrefs::LAUNCH_WINDOW);
208
209   *out_extension = extension;
210   *out_launch_container = launch_container;
211   return true;
212 }
213
214 // Parse two comma-separated integers from string. Return true on success.
215 bool ParseCommaSeparatedIntegers(const std::string& str,
216                                  int* ret_num1,
217                                  int* ret_num2) {
218   std::vector<std::string> dimensions;
219   base::SplitString(str, ',', &dimensions);
220   if (dimensions.size() != 2)
221     return false;
222
223   int num1, num2;
224   if (!base::StringToInt(dimensions[0], &num1) ||
225       !base::StringToInt(dimensions[1], &num2))
226     return false;
227
228   *ret_num1 = num1;
229   *ret_num2 = num2;
230   return true;
231 }
232
233 void RecordCmdLineAppHistogram(extensions::Manifest::Type app_type) {
234   CoreAppLauncherHandler::RecordAppLaunchType(
235       extension_misc::APP_LAUNCH_CMD_LINE_APP,
236       app_type);
237 }
238
239 void RecordAppLaunches(Profile* profile,
240                        const std::vector<GURL>& cmd_line_urls,
241                        StartupTabs& autolaunch_tabs) {
242   ExtensionService* extension_service = profile->GetExtensionService();
243   DCHECK(extension_service);
244   for (size_t i = 0; i < cmd_line_urls.size(); ++i) {
245     const extensions::Extension* extension =
246         extension_service->GetInstalledApp(cmd_line_urls.at(i));
247     if (extension) {
248       CoreAppLauncherHandler::RecordAppLaunchType(
249           extension_misc::APP_LAUNCH_CMD_LINE_URL,
250           extension->GetType());
251     }
252   }
253   for (size_t i = 0; i < autolaunch_tabs.size(); ++i) {
254     const extensions::Extension* extension =
255         extension_service->GetInstalledApp(autolaunch_tabs.at(i).url);
256     if (extension) {
257       CoreAppLauncherHandler::RecordAppLaunchType(
258           extension_misc::APP_LAUNCH_AUTOLAUNCH,
259           extension->GetType());
260     }
261   }
262 }
263
264 bool IsNewTabURL(Profile* profile, const GURL& url) {
265   GURL ntp_url(chrome::kChromeUINewTabURL);
266   return url == ntp_url ||
267          (url.is_empty() && profile->GetHomePage() == ntp_url);
268 }
269
270 class WebContentsCloseObserver : public content::NotificationObserver {
271  public:
272   WebContentsCloseObserver() : contents_(NULL) {}
273   virtual ~WebContentsCloseObserver() {}
274
275   void SetContents(content::WebContents* contents) {
276     DCHECK(!contents_);
277     contents_ = contents;
278
279     registrar_.Add(this,
280                    content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
281                    content::Source<content::WebContents>(contents_));
282   }
283
284   content::WebContents* contents() { return contents_; }
285
286  private:
287   // content::NotificationObserver overrides:
288   virtual void Observe(int type,
289                        const content::NotificationSource& source,
290                        const content::NotificationDetails& details) OVERRIDE {
291     DCHECK_EQ(type, content::NOTIFICATION_WEB_CONTENTS_DESTROYED);
292     contents_ = NULL;
293   }
294
295   content::WebContents* contents_;
296   content::NotificationRegistrar registrar_;
297
298   DISALLOW_COPY_AND_ASSIGN(WebContentsCloseObserver);
299 };
300
301 const Extension* GetDisabledPlatformApp(Profile* profile,
302                                         const std::string& extension_id) {
303   ExtensionService* service =
304       extensions::ExtensionSystem::Get(profile)->extension_service();
305   const Extension* extension = service->GetExtensionById(extension_id, true);
306   return extension && extension->is_platform_app() ? extension : NULL;
307 }
308
309 }  // namespace
310
311 namespace internals {
312
313 GURL GetWelcomePageURL() {
314   std::string welcome_url = l10n_util::GetStringUTF8(IDS_WELCOME_PAGE_URL);
315   return GURL(welcome_url);
316 }
317
318 }  // namespace internals
319
320 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
321     const base::FilePath& cur_dir,
322     const CommandLine& command_line,
323     chrome::startup::IsFirstRun is_first_run)
324     : cur_dir_(cur_dir),
325       command_line_(command_line),
326       profile_(NULL),
327       browser_creator_(NULL),
328       is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
329 }
330
331 StartupBrowserCreatorImpl::StartupBrowserCreatorImpl(
332     const base::FilePath& cur_dir,
333     const CommandLine& command_line,
334     StartupBrowserCreator* browser_creator,
335     chrome::startup::IsFirstRun is_first_run)
336     : cur_dir_(cur_dir),
337       command_line_(command_line),
338       profile_(NULL),
339       browser_creator_(browser_creator),
340       is_first_run_(is_first_run == chrome::startup::IS_FIRST_RUN) {
341 }
342
343 StartupBrowserCreatorImpl::~StartupBrowserCreatorImpl() {
344 }
345
346 bool StartupBrowserCreatorImpl::Launch(Profile* profile,
347                                        const std::vector<GURL>& urls_to_open,
348                                        bool process_startup,
349                                        chrome::HostDesktopType desktop_type) {
350   DCHECK(profile);
351   profile_ = profile;
352
353   if (command_line_.HasSwitch(switches::kDnsLogDetails))
354     chrome_browser_net::EnablePredictorDetailedLog(true);
355   if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
356       profile->GetNetworkPredictor()) {
357     profile->GetNetworkPredictor()->EnablePredictor(false);
358   }
359
360   AppListService::InitAll(profile);
361   if (command_line_.HasSwitch(switches::kAppId)) {
362     std::string app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
363     const Extension* extension = GetDisabledPlatformApp(profile, app_id);
364     // If |app_id| is a disabled platform app we handle it specially here,
365     // otherwise it will be handled below.
366     if (extension) {
367       RecordCmdLineAppHistogram(extensions::Manifest::TYPE_PLATFORM_APP);
368       AppLaunchParams params(profile, extension,
369                              extension_misc::LAUNCH_NONE, NEW_WINDOW);
370       params.command_line = &command_line_;
371       params.current_directory = cur_dir_;
372       OpenApplicationWithReenablePrompt(params);
373       return true;
374     }
375   } else if (command_line_.HasSwitch(switches::kShowAppList)) {
376     // This switch is used for shortcuts on the native desktop.
377     AppListService::RecordShowTimings(command_line_);
378     AppListService::Get(chrome::HOST_DESKTOP_TYPE_NATIVE)->
379         ShowForProfile(profile);
380     return true;
381   }
382
383   // Open the required browser windows and tabs. First, see if
384   // we're being run as an application window. If so, the user
385   // opened an app shortcut.  Don't restore tabs or open initial
386   // URLs in that case. The user should see the window as an app,
387   // not as chrome.
388   // Special case is when app switches are passed but we do want to restore
389   // session. In that case open app window + focus it after session is restored.
390   content::WebContents* app_contents = NULL;
391   if (OpenApplicationWindow(profile, &app_contents)) {
392     RecordLaunchModeHistogram(LM_AS_WEBAPP);
393   } else {
394     RecordLaunchModeHistogram(urls_to_open.empty() ?
395                               LM_TO_BE_DECIDED : LM_WITH_URLS);
396
397     ProcessLaunchURLs(process_startup, urls_to_open, desktop_type);
398
399     // If this is an app launch, but we didn't open an app window, it may
400     // be an app tab.
401     OpenApplicationTab(profile);
402
403 #if defined(OS_MACOSX)
404     if (process_startup) {
405       // Check whether the auto-update system needs to be promoted from user
406       // to system.
407       KeystoneInfoBar::PromotionInfoBar(profile);
408     }
409 #endif
410   }
411
412 #if defined(OS_WIN)
413   if (process_startup)
414     ShellIntegration::MigrateChromiumShortcuts();
415 #endif  // defined(OS_WIN)
416
417 #if defined(ENABLE_EXTENSIONS)
418   // If we deferred creation of background extension hosts, we want to create
419   // them now that the session (if any) has been restored.
420   ExtensionProcessManager* process_manager =
421       extensions::ExtensionSystem::Get(profile)->process_manager();
422   process_manager->DeferBackgroundHostCreation(false);
423 #endif
424
425   return true;
426 }
427
428 void StartupBrowserCreatorImpl::ExtractOptionalAppWindowSize(
429     gfx::Rect* bounds) {
430   if (command_line_.HasSwitch(switches::kAppWindowSize)) {
431     int width, height;
432     width = height = 0;
433     std::string switch_value =
434         command_line_.GetSwitchValueASCII(switches::kAppWindowSize);
435     if (ParseCommaSeparatedIntegers(switch_value, &width, &height)) {
436       // TODO(scottmg): NativeScreen might be wrong. http://crbug.com/133312
437       const gfx::Rect work_area =
438           gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().work_area();
439       width = std::min(width, work_area.width());
440       height = std::min(height, work_area.height());
441       bounds->set_size(gfx::Size(width, height));
442       bounds->set_x((work_area.width() - bounds->width()) / 2);
443       // TODO(nkostylev): work_area does include launcher but should not.
444       // Launcher auto hide pref is synced and is most likely not applied here.
445       bounds->set_y((work_area.height() - bounds->height()) / 2);
446     }
447   }
448 }
449
450 bool StartupBrowserCreatorImpl::IsAppLaunch(std::string* app_url,
451                                             std::string* app_id) {
452   if (command_line_.HasSwitch(switches::kApp)) {
453     if (app_url)
454       *app_url = command_line_.GetSwitchValueASCII(switches::kApp);
455     return true;
456   }
457   if (command_line_.HasSwitch(switches::kAppId)) {
458     if (app_id)
459       *app_id = command_line_.GetSwitchValueASCII(switches::kAppId);
460     return true;
461   }
462   return false;
463 }
464
465 bool StartupBrowserCreatorImpl::OpenApplicationTab(Profile* profile) {
466   std::string app_id;
467   // App shortcuts to URLs always open in an app window.  Because this
468   // function will open an app that should be in a tab, there is no need
469   // to look at the app URL.  OpenApplicationWindow() will open app url
470   // shortcuts.
471   if (!IsAppLaunch(NULL, &app_id) || app_id.empty())
472     return false;
473
474   extension_misc::LaunchContainer launch_container;
475   const Extension* extension;
476   if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
477     return false;
478
479   // If the user doesn't want to open a tab, fail.
480   if (launch_container != extension_misc::LAUNCH_TAB)
481     return false;
482
483   RecordCmdLineAppHistogram(extension->GetType());
484
485   WebContents* app_tab = OpenApplication(AppLaunchParams(
486       profile, extension, extension_misc::LAUNCH_TAB, NEW_FOREGROUND_TAB));
487   return (app_tab != NULL);
488 }
489
490 bool StartupBrowserCreatorImpl::OpenApplicationWindow(
491     Profile* profile,
492     content::WebContents** out_app_contents) {
493   // Set |out_app_contents| to NULL early on (just in case).
494   if (out_app_contents)
495     *out_app_contents = NULL;
496
497   std::string url_string, app_id;
498   if (!IsAppLaunch(&url_string, &app_id))
499     return false;
500
501   // This can fail if the app_id is invalid.  It can also fail if the
502   // extension is external, and has not yet been installed.
503   // TODO(skerner): Do something reasonable here. Pop up a warning panel?
504   // Open an URL to the gallery page of the extension id?
505   if (!app_id.empty()) {
506     extension_misc::LaunchContainer launch_container;
507     const Extension* extension;
508     if (!GetAppLaunchContainer(profile, app_id, &extension, &launch_container))
509       return false;
510
511     // TODO(skerner): Could pass in |extension| and |launch_container|,
512     // and avoid calling GetAppLaunchContainer() both here and in
513     // OpenApplicationTab().
514
515     if (launch_container == extension_misc::LAUNCH_TAB)
516       return false;
517
518     RecordCmdLineAppHistogram(extension->GetType());
519
520     AppLaunchParams params(profile, extension, launch_container, NEW_WINDOW);
521     params.command_line = &command_line_;
522     params.current_directory = cur_dir_;
523     WebContents* tab_in_app_window = OpenApplication(params);
524
525     if (out_app_contents)
526       *out_app_contents = tab_in_app_window;
527
528     // Platform apps fire off a launch event which may or may not open a window.
529     return (tab_in_app_window != NULL || extension->is_platform_app());
530   }
531
532   if (url_string.empty())
533     return false;
534
535 #if defined(OS_WIN)  // Fix up Windows shortcuts.
536   ReplaceSubstringsAfterOffset(&url_string, 0, "\\x", "%");
537 #endif
538   GURL url(url_string);
539
540   // Restrict allowed URLs for --app switch.
541   if (!url.is_empty() && url.is_valid()) {
542     ChildProcessSecurityPolicy* policy =
543         ChildProcessSecurityPolicy::GetInstance();
544     if (policy->IsWebSafeScheme(url.scheme()) ||
545         url.SchemeIs(chrome::kFileScheme)) {
546       const extensions::Extension* extension =
547           profile->GetExtensionService()->GetInstalledApp(url);
548       if (extension) {
549         RecordCmdLineAppHistogram(extension->GetType());
550       } else {
551         CoreAppLauncherHandler::RecordAppLaunchType(
552             extension_misc::APP_LAUNCH_CMD_LINE_APP_LEGACY,
553             extensions::Manifest::TYPE_HOSTED_APP);
554       }
555
556       gfx::Rect override_bounds;
557       ExtractOptionalAppWindowSize(&override_bounds);
558
559       WebContents* app_tab = OpenAppShortcutWindow(profile,
560                                                    url,
561                                                    override_bounds);
562
563       if (out_app_contents)
564         *out_app_contents = app_tab;
565
566       return (app_tab != NULL);
567     }
568   }
569   return false;
570 }
571
572 void StartupBrowserCreatorImpl::ProcessLaunchURLs(
573     bool process_startup,
574     const std::vector<GURL>& urls_to_open,
575     chrome::HostDesktopType desktop_type) {
576   // If we're starting up in "background mode" (no open browser window) then
577   // don't open any browser windows, unless kAutoLaunchAtStartup is also
578   // specified.
579   if (process_startup &&
580       command_line_.HasSwitch(switches::kNoStartupWindow) &&
581       !command_line_.HasSwitch(switches::kAutoLaunchAtStartup)) {
582     return;
583   }
584
585 // TODO(tapted): Move this to startup_browser_creator_win.cc after refactor.
586 #if defined(OS_WIN)
587   if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
588     // See if there are apps for this profile that should be launched on startup
589     // due to a switch from Metro mode.
590     app_metro_launch::HandleAppLaunchForMetroRestart(profile_);
591   }
592 #endif
593
594   if (process_startup && ProcessStartupURLs(urls_to_open, desktop_type)) {
595     // ProcessStartupURLs processed the urls, nothing else to do.
596     return;
597   }
598
599   chrome::startup::IsProcessStartup is_process_startup = process_startup ?
600       chrome::startup::IS_PROCESS_STARTUP :
601       chrome::startup::IS_NOT_PROCESS_STARTUP;
602   if (!process_startup) {
603     // Even if we're not starting a new process, this may conceptually be
604     // "startup" for the user and so should be handled in a similar way.  Eg.,
605     // Chrome may have been running in the background due to an app with a
606     // background page being installed, or running with only an app window
607     // displayed.
608     SessionService* service =
609         SessionServiceFactory::GetForProfileForSessionRestore(profile_);
610     if (service && service->ShouldNewWindowStartSession()) {
611       // Restore the last session if any.
612       if (!HasPendingUncleanExit(profile_) &&
613           service->RestoreIfNecessary(urls_to_open)) {
614         return;
615       }
616       // Open user-specified URLs like pinned tabs and startup tabs.
617       Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
618       if (browser) {
619         AddInfoBarsIfNecessary(browser, is_process_startup);
620         return;
621       }
622     }
623   }
624
625   // Session startup didn't occur, open the urls.
626   Browser* browser = NULL;
627   std::vector<GURL> adjust_urls = urls_to_open;
628   if (adjust_urls.empty()) {
629     AddStartupURLs(&adjust_urls);
630     if (StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
631             profile_, adjust_urls))
632       return;
633   } else if (!command_line_.HasSwitch(switches::kOpenInNewWindow)) {
634     // Always open a list of urls in a window on the native desktop.
635     browser = chrome::FindTabbedBrowser(profile_, false,
636                                         chrome::HOST_DESKTOP_TYPE_NATIVE);
637   }
638   // This will launch a browser; prevent session restore.
639   StartupBrowserCreator::in_synchronous_profile_launch_ = true;
640   browser = OpenURLsInBrowser(browser, process_startup, adjust_urls,
641                               desktop_type);
642   StartupBrowserCreator::in_synchronous_profile_launch_ = false;
643   AddInfoBarsIfNecessary(browser, is_process_startup);
644 }
645
646 bool StartupBrowserCreatorImpl::ProcessStartupURLs(
647     const std::vector<GURL>& urls_to_open,
648     chrome::HostDesktopType desktop_type) {
649   VLOG(1) << "StartupBrowserCreatorImpl::ProcessStartupURLs";
650   SessionStartupPref pref =
651       StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
652   if (pref.type == SessionStartupPref::LAST)
653     VLOG(1) << "Pref: last";
654   else if (pref.type == SessionStartupPref::URLS)
655     VLOG(1) << "Pref: urls";
656   else if (pref.type == SessionStartupPref::DEFAULT)
657     VLOG(1) << "Pref: default";
658
659   apps::AppRestoreService* restore_service =
660       apps::AppRestoreServiceFactory::GetForProfile(profile_);
661   // NULL in incognito mode.
662   if (restore_service) {
663     restore_service->HandleStartup(apps::AppRestoreService::ShouldRestoreApps(
664         StartupBrowserCreator::WasRestarted()));
665   }
666
667   if (pref.type == SessionStartupPref::LAST) {
668     if (profile_->GetLastSessionExitType() == Profile::EXIT_CRASHED &&
669         !command_line_.HasSwitch(switches::kRestoreLastSession)) {
670       // The last session crashed. It's possible automatically loading the
671       // page will trigger another crash, locking the user out of chrome.
672       // To avoid this, don't restore on startup but instead show the crashed
673       // infobar.
674       VLOG(1) << "Unclean exit; not processing";
675       return false;
676     }
677
678     uint32 restore_behavior = SessionRestore::SYNCHRONOUS;
679     if (browser_defaults::kAlwaysCreateTabbedBrowserOnSessionRestore ||
680         CommandLine::ForCurrentProcess()->HasSwitch(
681             switches::kCreateBrowserOnStartupForTests)) {
682       restore_behavior |= SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
683     }
684
685 #if defined(OS_MACOSX)
686     // On Mac, when restoring a session with no windows, suppress the creation
687     // of a new window in the case where the system is launching Chrome via a
688     // login item or Lion's resume feature.
689     if (base::mac::WasLaunchedAsLoginOrResumeItem()) {
690       restore_behavior = restore_behavior &
691                          ~SessionRestore::ALWAYS_CREATE_TABBED_BROWSER;
692     }
693 #endif
694
695     // Pause the StartupTimer. Since the restore here is synchronous, we can
696     // keep these two metrics (browser startup time and session restore time)
697     // separate.
698     performance_monitor::StartupTimer::PauseTimer();
699
700     // The startup code only executes for browsers launched in desktop mode.
701     // i.e. HOST_DESKTOP_TYPE_NATIVE. Ash should never get here.
702     Browser* browser = SessionRestore::RestoreSession(
703         profile_, NULL, desktop_type, restore_behavior,
704         urls_to_open);
705
706     performance_monitor::StartupTimer::UnpauseTimer();
707
708     AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
709     return true;
710   }
711
712   Browser* browser = ProcessSpecifiedURLs(urls_to_open, desktop_type);
713   if (!browser)
714     return false;
715
716   AddInfoBarsIfNecessary(browser, chrome::startup::IS_PROCESS_STARTUP);
717
718   // Session restore may occur if the startup preference is "last" or if the
719   // crash infobar is displayed. Otherwise, it's safe for the DOM storage system
720   // to start deleting leftover data.
721   if (pref.type != SessionStartupPref::LAST &&
722       !HasPendingUncleanExit(profile_)) {
723     content::BrowserContext::GetDefaultStoragePartition(profile_)->
724         GetDOMStorageContext()->StartScavengingUnusedSessionStorage();
725   }
726
727   return true;
728 }
729
730 Browser* StartupBrowserCreatorImpl::ProcessSpecifiedURLs(
731     const std::vector<GURL>& urls_to_open,
732     chrome::HostDesktopType desktop_type) {
733   SessionStartupPref pref =
734       StartupBrowserCreator::GetSessionStartupPref(command_line_, profile_);
735   StartupTabs tabs;
736   // Pinned tabs should not be displayed when chrome is launched in incognito
737   // mode. Also, no pages should be opened automatically if the session
738   // crashed. Otherwise it might trigger another crash, locking the user out of
739   // chrome. The crash infobar is shown in this case.
740   if (!IncognitoModePrefs::ShouldLaunchIncognito(command_line_,
741                                                  profile_->GetPrefs()) &&
742       !HasPendingUncleanExit(profile_)) {
743     tabs = PinnedTabCodec::ReadPinnedTabs(profile_);
744   }
745
746   RecordAppLaunches(profile_, urls_to_open, tabs);
747
748   if (!urls_to_open.empty()) {
749     // If urls were specified on the command line, use them.
750     UrlsToTabs(urls_to_open, &tabs);
751   } else if (pref.type == SessionStartupPref::DEFAULT ||
752              (is_first_run_ &&
753               browser_creator_ && !browser_creator_->first_run_tabs_.empty())) {
754     std::vector<GURL> urls;
755     AddStartupURLs(&urls);
756     UrlsToTabs(urls, &tabs);
757   } else if (pref.type == SessionStartupPref::URLS && !pref.urls.empty() &&
758              !HasPendingUncleanExit(profile_)) {
759     // Only use the set of urls specified in preferences if nothing was
760     // specified on the command line. Filter out any urls that are to be
761     // restored by virtue of having been previously pinned.
762     AddUniqueURLs(pref.urls, &tabs);
763   } else if (pref.type == SessionStartupPref::HOMEPAGE) {
764     // If 'homepage' selected, either by the user or by a policy, we should
765     // have migrated them to another value.
766     NOTREACHED() << "SessionStartupPref has deprecated type HOMEPAGE";
767   }
768
769   if (tabs.empty())
770     return NULL;
771
772   Browser* browser = OpenTabsInBrowser(NULL, true, tabs, desktop_type);
773   return browser;
774 }
775
776 void StartupBrowserCreatorImpl::AddUniqueURLs(const std::vector<GURL>& urls,
777                                               StartupTabs* tabs) {
778   size_t num_existing_tabs = tabs->size();
779   for (size_t i = 0; i < urls.size(); ++i) {
780     bool in_tabs = false;
781     for (size_t j = 0; j < num_existing_tabs; ++j) {
782       if (urls[i] == (*tabs)[j].url) {
783         in_tabs = true;
784         break;
785       }
786     }
787     if (!in_tabs) {
788       StartupTab tab;
789       tab.is_pinned = false;
790       tab.url = urls[i];
791       tabs->push_back(tab);
792     }
793   }
794 }
795
796 Browser* StartupBrowserCreatorImpl::OpenURLsInBrowser(
797     Browser* browser,
798     bool process_startup,
799     const std::vector<GURL>& urls,
800     chrome::HostDesktopType desktop_type) {
801   StartupTabs tabs;
802   UrlsToTabs(urls, &tabs);
803   return OpenTabsInBrowser(browser, process_startup, tabs, desktop_type);
804 }
805
806 Browser* StartupBrowserCreatorImpl::OpenTabsInBrowser(
807     Browser* browser,
808     bool process_startup,
809     const StartupTabs& tabs,
810     chrome::HostDesktopType desktop_type) {
811   DCHECK(!tabs.empty());
812
813   // If we don't yet have a profile, try to use the one we're given from
814   // |browser|. While we may not end up actually using |browser| (since it
815   // could be a popup window), we can at least use the profile.
816   if (!profile_ && browser)
817     profile_ = browser->profile();
818
819   if (!browser || !browser->is_type_tabbed()) {
820     browser = new Browser(Browser::CreateParams(profile_, desktop_type));
821   } else {
822 #if defined(TOOLKIT_GTK)
823     // Setting the time of the last action on the window here allows us to steal
824     // focus, which is what the user wants when opening a new tab in an existing
825     // browser window.
826     gtk_util::SetWMLastUserActionTime(browser->window()->GetNativeWindow());
827 #endif
828   }
829
830   // In kiosk mode, we want to always be fullscreen, so switch to that now.
831   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
832     chrome::ToggleFullscreenMode(browser);
833
834   bool first_tab = true;
835   ProtocolHandlerRegistry* registry = profile_ ?
836       ProtocolHandlerRegistryFactory::GetForProfile(profile_) : NULL;
837   for (size_t i = 0; i < tabs.size(); ++i) {
838     // We skip URLs that we'd have to launch an external protocol handler for.
839     // This avoids us getting into an infinite loop asking ourselves to open
840     // a URL, should the handler be (incorrectly) configured to be us. Anyone
841     // asking us to open such a URL should really ask the handler directly.
842     bool handled_by_chrome = ProfileIOData::IsHandledURL(tabs[i].url) ||
843         (registry && registry->IsHandledProtocol(tabs[i].url.scheme()));
844     if (!process_startup && !handled_by_chrome)
845       continue;
846
847     int add_types = first_tab ? TabStripModel::ADD_ACTIVE :
848                                 TabStripModel::ADD_NONE;
849     add_types |= TabStripModel::ADD_FORCE_INDEX;
850     if (tabs[i].is_pinned)
851       add_types |= TabStripModel::ADD_PINNED;
852
853     chrome::NavigateParams params(browser, tabs[i].url,
854                                   content::PAGE_TRANSITION_AUTO_TOPLEVEL);
855     params.disposition = first_tab ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
856     params.tabstrip_add_types = add_types;
857     params.extension_app_id = tabs[i].app_id;
858
859 #if defined(ENABLE_RLZ)
860     if (process_startup && google_util::IsGoogleHomePageUrl(tabs[i].url)) {
861       params.extra_headers = RLZTracker::GetAccessPointHttpHeader(
862           RLZTracker::CHROME_HOME_PAGE);
863     }
864 #endif
865
866     chrome::Navigate(&params);
867
868     first_tab = false;
869   }
870   if (!browser->tab_strip_model()->GetActiveWebContents()) {
871     // TODO: this is a work around for 110909. Figure out why it's needed.
872     if (!browser->tab_strip_model()->count())
873       chrome::AddBlankTabAt(browser, -1, true);
874     else
875       browser->tab_strip_model()->ActivateTabAt(0, false);
876   }
877
878   // The default behavior is to show the window, as expressed by the default
879   // value of StartupBrowserCreated::show_main_browser_window_. If this was set
880   // to true ahead of this place, it means another task must have been spawned
881   // to take care of that.
882   if (!browser_creator_ || browser_creator_->show_main_browser_window())
883     browser->window()->Show();
884
885   return browser;
886 }
887
888 void StartupBrowserCreatorImpl::AddInfoBarsIfNecessary(
889     Browser* browser,
890     chrome::startup::IsProcessStartup is_process_startup) {
891   if (!browser || !profile_ || browser->tab_strip_model()->count() == 0)
892     return;
893
894   if (HasPendingUncleanExit(browser->profile()))
895     SessionCrashedInfoBarDelegate::Create(browser);
896
897   // The below info bars are only added to the first profile which is launched.
898   // Other profiles might be restoring the browsing sessions asynchronously,
899   // so we cannot add the info bars to the focused tabs here.
900   if (is_process_startup == chrome::startup::IS_PROCESS_STARTUP) {
901     chrome::ShowBadFlagsPrompt(browser);
902     if (!command_line_.HasSwitch(switches::kTestType)) {
903       GoogleApiKeysInfoBarDelegate::Create(InfoBarService::FromWebContents(
904           browser->tab_strip_model()->GetActiveWebContents()));
905     }
906
907     ObsoleteOSInfoBarDelegate::Create(InfoBarService::FromWebContents(
908         browser->tab_strip_model()->GetActiveWebContents()));
909
910 #if !defined(OS_CHROMEOS)
911     if (!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
912       // Generally, the default browser prompt should not be shown on first
913       // run. However, when the set-as-default dialog has been suppressed, we
914       // need to allow it.
915       if ((!is_first_run_ ||
916            (browser_creator_ &&
917             browser_creator_->is_default_browser_dialog_suppressed())) &&
918           !chrome::ShowAutolaunchPrompt(browser)) {
919         chrome::ShowDefaultBrowserPrompt(profile_,
920                                          browser->host_desktop_type());
921       }
922     }
923 #endif
924   }
925 }
926
927 void StartupBrowserCreatorImpl::AddStartupURLs(
928     std::vector<GURL>* startup_urls) const {
929   // TODO(atwilson): Simplify the logic that decides which tabs to open on
930   // start-up and make it more consistent. http://crbug.com/248883
931
932   // If we have urls specified by the first run master preferences use them
933   // and nothing else.
934   if (browser_creator_ && startup_urls->empty()) {
935     if (!browser_creator_->first_run_tabs_.empty()) {
936       std::vector<GURL>::iterator it =
937           browser_creator_->first_run_tabs_.begin();
938       while (it != browser_creator_->first_run_tabs_.end()) {
939         // Replace magic names for the actual urls.
940         if (it->host() == "new_tab_page") {
941           startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
942         } else if (it->host() == "welcome_page") {
943           startup_urls->push_back(internals::GetWelcomePageURL());
944         } else {
945           startup_urls->push_back(*it);
946         }
947         ++it;
948       }
949       browser_creator_->first_run_tabs_.clear();
950     }
951   }
952
953   // Otherwise open at least the new tab page (and the welcome page, if this
954   // is the first time the browser is being started), or the set of URLs
955   // specified on the command line.
956   if (startup_urls->empty()) {
957     startup_urls->push_back(GURL(chrome::kChromeUINewTabURL));
958     if (first_run::ShouldShowWelcomePage())
959       startup_urls->push_back(internals::GetWelcomePageURL());
960   }
961
962   if (signin::ShouldShowPromoAtStartup(profile_, is_first_run_)) {
963     signin::DidShowPromoAtStartup(profile_);
964
965     const GURL sync_promo_url = signin::GetPromoURL(signin::SOURCE_START_PAGE,
966                                                     false);
967
968     // No need to add if the sync promo is already in the startup list.
969     bool add_promo = true;
970     for (std::vector<GURL>::const_iterator it = startup_urls->begin();
971          it != startup_urls->end(); ++it) {
972       if (*it == sync_promo_url) {
973         add_promo = false;
974         break;
975       }
976     }
977
978     if (add_promo) {
979       // If the first URL is the NTP, replace it with the sync promo. This
980       // behavior is desired because completing or skipping the sync promo
981       // causes a redirect to the NTP.
982       if (!startup_urls->empty() && IsNewTabURL(profile_, startup_urls->at(0)))
983         startup_urls->at(0) = sync_promo_url;
984       else
985         startup_urls->insert(startup_urls->begin(), sync_promo_url);
986     }
987   }
988 }
989
990 #if !defined(OS_WIN)
991 // static
992 bool StartupBrowserCreatorImpl::OpenStartupURLsInExistingBrowser(
993     Profile* profile,
994     const std::vector<GURL>& startup_urls) {
995   return false;
996 }
997 #endif