Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / browser_browsertest.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 <string>
6
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/compiler_specific.h"
10 #include "base/files/file_path.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/sys_info.h"
15 #include "chrome/app/chrome_command_ids.h"
16 #include "chrome/browser/chrome_content_browser_client.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/command_updater.h"
19 #include "chrome/browser/content_settings/host_content_settings_map.h"
20 #include "chrome/browser/defaults.h"
21 #include "chrome/browser/devtools/devtools_window_testing.h"
22 #include "chrome/browser/extensions/extension_browsertest.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/extensions/tab_helper.h"
25 #include "chrome/browser/first_run/first_run.h"
26 #include "chrome/browser/lifetime/application_lifetime.h"
27 #include "chrome/browser/prefs/incognito_mode_prefs.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/profiles/profile_manager.h"
30 #include "chrome/browser/search/search.h"
31 #include "chrome/browser/sessions/session_backend.h"
32 #include "chrome/browser/sessions/session_service_factory.h"
33 #include "chrome/browser/translate/chrome_translate_client.h"
34 #include "chrome/browser/translate/cld_data_harness.h"
35 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog.h"
36 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h"
37 #include "chrome/browser/ui/app_modal_dialogs/javascript_app_modal_dialog.h"
38 #include "chrome/browser/ui/app_modal_dialogs/native_app_modal_dialog.h"
39 #include "chrome/browser/ui/browser.h"
40 #include "chrome/browser/ui/browser_command_controller.h"
41 #include "chrome/browser/ui/browser_commands.h"
42 #include "chrome/browser/ui/browser_finder.h"
43 #include "chrome/browser/ui/browser_iterator.h"
44 #include "chrome/browser/ui/browser_navigator.h"
45 #include "chrome/browser/ui/browser_tabstrip.h"
46 #include "chrome/browser/ui/browser_ui_prefs.h"
47 #include "chrome/browser/ui/browser_window.h"
48 #include "chrome/browser/ui/extensions/application_launch.h"
49 #include "chrome/browser/ui/host_desktop.h"
50 #include "chrome/browser/ui/startup/startup_browser_creator.h"
51 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
52 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
53 #include "chrome/browser/ui/tabs/tab_strip_model.h"
54 #include "chrome/common/chrome_switches.h"
55 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
56 #include "chrome/common/pref_names.h"
57 #include "chrome/common/url_constants.h"
58 #include "chrome/test/base/in_process_browser_test.h"
59 #include "chrome/test/base/test_switches.h"
60 #include "chrome/test/base/ui_test_utils.h"
61 #include "components/translate/core/browser/language_state.h"
62 #include "components/translate/core/common/language_detection_details.h"
63 #include "content/public/browser/favicon_status.h"
64 #include "content/public/browser/host_zoom_map.h"
65 #include "content/public/browser/interstitial_page.h"
66 #include "content/public/browser/interstitial_page_delegate.h"
67 #include "content/public/browser/navigation_entry.h"
68 #include "content/public/browser/notification_service.h"
69 #include "content/public/browser/render_frame_host.h"
70 #include "content/public/browser/render_process_host.h"
71 #include "content/public/browser/render_view_host.h"
72 #include "content/public/browser/render_widget_host_view.h"
73 #include "content/public/browser/resource_context.h"
74 #include "content/public/browser/web_contents.h"
75 #include "content/public/browser/web_contents_observer.h"
76 #include "content/public/common/frame_navigate_params.h"
77 #include "content/public/common/page_transition_types.h"
78 #include "content/public/common/renderer_preferences.h"
79 #include "content/public/common/url_constants.h"
80 #include "content/public/test/browser_test_utils.h"
81 #include "content/public/test/test_navigation_observer.h"
82 #include "extensions/browser/extension_system.h"
83 #include "extensions/browser/uninstall_reason.h"
84 #include "extensions/common/extension.h"
85 #include "extensions/common/extension_set.h"
86 #include "grit/chromium_strings.h"
87 #include "grit/generated_resources.h"
88 #include "net/dns/mock_host_resolver.h"
89 #include "net/test/spawned_test_server/spawned_test_server.h"
90 #include "ui/base/l10n/l10n_util.h"
91
92 #if defined(OS_MACOSX)
93 #include "base/mac/mac_util.h"
94 #include "base/mac/scoped_nsautorelease_pool.h"
95 #include "chrome/browser/ui/cocoa/run_loop_testing.h"
96 #endif
97
98 #if defined(OS_WIN)
99 #include "base/i18n/rtl.h"
100 #include "chrome/browser/browser_process.h"
101 #endif
102
103 using base::ASCIIToUTF16;
104 using content::InterstitialPage;
105 using content::HostZoomMap;
106 using content::NavigationController;
107 using content::NavigationEntry;
108 using content::OpenURLParams;
109 using content::Referrer;
110 using content::WebContents;
111 using content::WebContentsObserver;
112 using extensions::Extension;
113
114 namespace {
115
116 const char* kBeforeUnloadHTML =
117     "<html><head><title>beforeunload</title></head><body>"
118     "<script>window.onbeforeunload=function(e){return 'foo'}</script>"
119     "</body></html>";
120
121 const char* kOpenNewBeforeUnloadPage =
122     "w=window.open(); w.onbeforeunload=function(e){return 'foo'};";
123
124 const base::FilePath::CharType* kBeforeUnloadFile =
125     FILE_PATH_LITERAL("beforeunload.html");
126
127 const base::FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
128 const base::FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html");
129
130 const base::FilePath::CharType kDocRoot[] =
131     FILE_PATH_LITERAL("chrome/test/data");
132
133 // Given a page title, returns the expected window caption string.
134 base::string16 WindowCaptionFromPageTitle(const base::string16& page_title) {
135 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
136   // On Mac or ChromeOS, we don't want to suffix the page title with
137   // the application name.
138   if (page_title.empty())
139     return l10n_util::GetStringUTF16(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);
140   return page_title;
141 #else
142   if (page_title.empty())
143     return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
144
145   return l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT,
146                                     page_title);
147 #endif
148 }
149
150 // Returns the number of active RenderProcessHosts.
151 int CountRenderProcessHosts() {
152   int result = 0;
153   for (content::RenderProcessHost::iterator i(
154           content::RenderProcessHost::AllHostsIterator());
155        !i.IsAtEnd(); i.Advance())
156     ++result;
157   return result;
158 }
159
160 class MockTabStripModelObserver : public TabStripModelObserver {
161  public:
162   MockTabStripModelObserver() : closing_count_(0) {}
163
164   virtual void TabClosingAt(TabStripModel* tab_strip_model,
165                             WebContents* contents,
166                             int index) OVERRIDE {
167     ++closing_count_;
168   }
169
170   int closing_count() const { return closing_count_; }
171
172  private:
173   int closing_count_;
174
175   DISALLOW_COPY_AND_ASSIGN(MockTabStripModelObserver);
176 };
177
178 class InterstitialObserver : public content::WebContentsObserver {
179  public:
180   InterstitialObserver(content::WebContents* web_contents,
181                        const base::Closure& attach_callback,
182                        const base::Closure& detach_callback)
183       : WebContentsObserver(web_contents),
184         attach_callback_(attach_callback),
185         detach_callback_(detach_callback) {
186   }
187
188   virtual void DidAttachInterstitialPage() OVERRIDE {
189     attach_callback_.Run();
190   }
191
192   virtual void DidDetachInterstitialPage() OVERRIDE {
193     detach_callback_.Run();
194   }
195
196  private:
197   base::Closure attach_callback_;
198   base::Closure detach_callback_;
199
200   DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
201 };
202
203 // Causes the browser to swap processes on a redirect to an HTTPS URL.
204 class TransferHttpsRedirectsContentBrowserClient
205     : public chrome::ChromeContentBrowserClient {
206  public:
207   virtual bool ShouldSwapProcessesForRedirect(
208       content::ResourceContext* resource_context,
209       const GURL& current_url,
210       const GURL& new_url) OVERRIDE {
211     return new_url.SchemeIs(url::kHttpsScheme);
212   }
213 };
214
215 // Used by CloseWithAppMenuOpen. Invokes CloseWindow on the supplied browser.
216 void CloseWindowCallback(Browser* browser) {
217   chrome::CloseWindow(browser);
218 }
219
220 // Used by CloseWithAppMenuOpen. Posts a CloseWindowCallback and shows the app
221 // menu.
222 void RunCloseWithAppMenuCallback(Browser* browser) {
223   // ShowAppMenu is modal under views. Schedule a task that closes the window.
224   base::MessageLoop::current()->PostTask(
225       FROM_HERE, base::Bind(&CloseWindowCallback, browser));
226   chrome::ShowAppMenu(browser);
227 }
228
229 // Displays "INTERSTITIAL" while the interstitial is attached.
230 // (InterstitialPage can be used in a test directly, but there would be no way
231 // to visually tell if it is showing or not.)
232 class TestInterstitialPage : public content::InterstitialPageDelegate {
233  public:
234   TestInterstitialPage(WebContents* tab, bool new_navigation, const GURL& url) {
235     interstitial_page_ = InterstitialPage::Create(
236         tab, new_navigation, url , this);
237     interstitial_page_->Show();
238   }
239   virtual ~TestInterstitialPage() { }
240   void Proceed() {
241     interstitial_page_->Proceed();
242   }
243   void DontProceed() {
244     interstitial_page_->DontProceed();
245   }
246
247   virtual std::string GetHTMLContents() OVERRIDE {
248     return "<h1>INTERSTITIAL</h1>";
249   }
250
251  private:
252   InterstitialPage* interstitial_page_;  // Owns us.
253 };
254
255 class RenderViewSizeObserver : public content::WebContentsObserver {
256  public:
257   RenderViewSizeObserver(content::WebContents* web_contents,
258                          BrowserWindow* browser_window)
259       : WebContentsObserver(web_contents),
260         browser_window_(browser_window) {
261   }
262
263   void GetSizeForRenderViewHost(
264       content::RenderViewHost* render_view_host,
265       gfx::Size* rwhv_create_size,
266       gfx::Size* rwhv_commit_size,
267       gfx::Size* wcv_commit_size) {
268     RenderViewSizes::const_iterator result = render_view_sizes_.end();
269     result = render_view_sizes_.find(render_view_host);
270     if (result != render_view_sizes_.end()) {
271       *rwhv_create_size = result->second.rwhv_create_size;
272       *rwhv_commit_size = result->second.rwhv_commit_size;
273       *wcv_commit_size = result->second.wcv_commit_size;
274     }
275   }
276
277   void set_wcv_resize_insets(const gfx::Size& wcv_resize_insets) {
278     wcv_resize_insets_ = wcv_resize_insets;
279   }
280
281   // Cache the size when RenderViewHost is first created.
282   virtual void RenderViewCreated(
283       content::RenderViewHost* render_view_host) OVERRIDE {
284     render_view_sizes_[render_view_host].rwhv_create_size =
285         render_view_host->GetView()->GetViewBounds().size();
286   }
287
288   // Enlarge WebContentsView by |wcv_resize_insets_| while the navigation entry
289   // is pending.
290   virtual void DidStartNavigationToPendingEntry(
291       const GURL& url,
292       NavigationController::ReloadType reload_type) OVERRIDE {
293     if (wcv_resize_insets_.IsEmpty())
294       return;
295     // Resizing the main browser window by |wcv_resize_insets_| will
296     // automatically resize the WebContentsView by the same amount.
297     // Just resizing WebContentsView directly doesn't work on Linux, because the
298     // next automatic layout of the browser window will resize WebContentsView
299     // back to the previous size.  To make it consistent, resize main browser
300     // window on all platforms.
301     gfx::Rect bounds(browser_window_->GetBounds());
302     gfx::Size size(bounds.size());
303     size.Enlarge(wcv_resize_insets_.width(), wcv_resize_insets_.height());
304     bounds.set_size(size);
305     browser_window_->SetBounds(bounds);
306     // Let the message loop run so that resize actually takes effect.
307     content::RunAllPendingInMessageLoop();
308   }
309
310   // Cache the sizes of RenderWidgetHostView and WebContentsView when the
311   // navigation entry is committed, which is before
312   // WebContentsDelegate::DidNavigateMainFramePostCommit is called.
313   virtual void NavigationEntryCommitted(
314       const content::LoadCommittedDetails& details) OVERRIDE {
315     content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
316     render_view_sizes_[rvh].rwhv_commit_size =
317         web_contents()->GetRenderWidgetHostView()->GetViewBounds().size();
318     render_view_sizes_[rvh].wcv_commit_size =
319         web_contents()->GetContainerBounds().size();
320   }
321
322  private:
323   struct Sizes {
324     gfx::Size rwhv_create_size;  // Size of RenderWidgetHostView when created.
325     gfx::Size rwhv_commit_size;  // Size of RenderWidgetHostView when committed.
326     gfx::Size wcv_commit_size;   // Size of WebContentsView when committed.
327   };
328
329   typedef std::map<content::RenderViewHost*, Sizes> RenderViewSizes;
330   RenderViewSizes render_view_sizes_;
331   // Enlarge WebContentsView by this size insets in
332   // DidStartNavigationToPendingEntry.
333   gfx::Size wcv_resize_insets_;
334   BrowserWindow* browser_window_;  // Weak ptr.
335
336   DISALLOW_COPY_AND_ASSIGN(RenderViewSizeObserver);
337 };
338
339 }  // namespace
340
341 class BrowserTest : public ExtensionBrowserTest {
342  protected:
343   // In RTL locales wrap the page title with RTL embedding characters so that it
344   // matches the value returned by GetWindowTitle().
345   base::string16 LocaleWindowCaptionFromPageTitle(
346       const base::string16& expected_title) {
347     base::string16 page_title = WindowCaptionFromPageTitle(expected_title);
348 #if defined(OS_WIN)
349     std::string locale = g_browser_process->GetApplicationLocale();
350     if (base::i18n::GetTextDirectionForLocale(locale.c_str()) ==
351         base::i18n::RIGHT_TO_LEFT) {
352       base::i18n::WrapStringWithLTRFormatting(&page_title);
353     }
354
355     return page_title;
356 #else
357     // Do we need to use the above code on POSIX as well?
358     return page_title;
359 #endif
360   }
361
362   // Returns the app extension aptly named "App Test".
363   const Extension* GetExtension() {
364     const extensions::ExtensionSet* extensions =
365         extensions::ExtensionSystem::Get(
366             browser()->profile())->extension_service()->extensions();
367     for (extensions::ExtensionSet::const_iterator it = extensions->begin();
368          it != extensions->end(); ++it) {
369       if ((*it)->name() == "App Test")
370         return it->get();
371     }
372     NOTREACHED();
373     return NULL;
374   }
375 };
376
377 // Launch the app on a page with no title, check that the app title was set
378 // correctly.
379 IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {
380 #if defined(OS_WIN) && defined(USE_ASH)
381   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
382   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
383     return;
384 #endif
385
386   ui_test_utils::NavigateToURL(
387       browser(), ui_test_utils::GetTestUrl(
388                      base::FilePath(base::FilePath::kCurrentDirectory),
389                      base::FilePath(kTitle1File)));
390   EXPECT_EQ(LocaleWindowCaptionFromPageTitle(ASCIIToUTF16("title1.html")),
391             browser()->GetWindowTitleForCurrentTab());
392   base::string16 tab_title;
393   ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
394   EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title);
395 }
396
397 // Launch the app, navigate to a page with a title, check that the app title
398 // was set correctly.
399 IN_PROC_BROWSER_TEST_F(BrowserTest, Title) {
400 #if defined(OS_WIN) && defined(USE_ASH)
401   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
402   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
403     return;
404 #endif
405
406   ui_test_utils::NavigateToURL(
407       browser(), ui_test_utils::GetTestUrl(
408                      base::FilePath(base::FilePath::kCurrentDirectory),
409                      base::FilePath(kTitle2File)));
410   const base::string16 test_title(ASCIIToUTF16("Title Of Awesomeness"));
411   EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),
412             browser()->GetWindowTitleForCurrentTab());
413   base::string16 tab_title;
414   ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
415   EXPECT_EQ(test_title, tab_title);
416 }
417
418 IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {
419   GURL url(ui_test_utils::GetTestUrl(base::FilePath(
420       base::FilePath::kCurrentDirectory), base::FilePath(kTitle1File)));
421   ui_test_utils::NavigateToURL(browser(), url);
422   AddTabAtIndex(0, url, content::PAGE_TRANSITION_TYPED);
423   EXPECT_EQ(2, browser()->tab_strip_model()->count());
424   EXPECT_EQ(0, browser()->tab_strip_model()->active_index());
425   WebContents* second_tab = browser()->tab_strip_model()->GetWebContentsAt(1);
426   ASSERT_TRUE(second_tab);
427   second_tab->GetMainFrame()->ExecuteJavaScript(
428       ASCIIToUTF16("alert('Activate!');"));
429   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
430   alert->CloseModalDialog();
431   EXPECT_EQ(2, browser()->tab_strip_model()->count());
432   EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
433 }
434
435
436 #if defined(OS_WIN) && !defined(NDEBUG)
437 // http://crbug.com/114859. Times out frequently on Windows.
438 #define MAYBE_ThirtyFourTabs DISABLED_ThirtyFourTabs
439 #else
440 #define MAYBE_ThirtyFourTabs ThirtyFourTabs
441 #endif
442
443 // Create 34 tabs and verify that a lot of processes have been created. The
444 // exact number of processes depends on the amount of memory. Previously we
445 // had a hard limit of 31 processes and this test is mainly directed at
446 // verifying that we don't crash when we pass this limit.
447 // Warning: this test can take >30 seconds when running on a slow (low
448 // memory?) Mac builder.
449 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_ThirtyFourTabs) {
450   GURL url(ui_test_utils::GetTestUrl(base::FilePath(
451       base::FilePath::kCurrentDirectory), base::FilePath(kTitle2File)));
452
453   // There is one initial tab.
454   const int kTabCount = 34;
455   for (int ix = 0; ix != (kTabCount - 1); ++ix) {
456     chrome::AddSelectedTabWithURL(browser(), url,
457                                   content::PAGE_TRANSITION_TYPED);
458   }
459   EXPECT_EQ(kTabCount, browser()->tab_strip_model()->count());
460
461   // See GetMaxRendererProcessCount() in
462   // content/browser/renderer_host/render_process_host_impl.cc
463   // for the algorithm to decide how many processes to create.
464   const int kExpectedProcessCount =
465 #if defined(ARCH_CPU_64_BITS)
466       17;
467 #else
468       25;
469 #endif
470   if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
471     EXPECT_GE(CountRenderProcessHosts(), kExpectedProcessCount);
472   } else {
473     EXPECT_LT(CountRenderProcessHosts(), kExpectedProcessCount);
474   }
475 }
476
477 // Test that a browser-initiated navigation to an aborted URL load leaves around
478 // a pending entry if we start from the NTP but not from a normal page.
479 // See http://crbug.com/355537.
480 IN_PROC_BROWSER_TEST_F(BrowserTest, ClearPendingOnFailUnlessNTP) {
481   ASSERT_TRUE(test_server()->Start());
482   WebContents* web_contents =
483       browser()->tab_strip_model()->GetActiveWebContents();
484   GURL ntp_url(chrome::GetNewTabPageURL(browser()->profile()));
485   ui_test_utils::NavigateToURL(browser(), ntp_url);
486
487   // Navigate to a 204 URL (aborts with no content) on the NTP and make sure it
488   // sticks around so that the user can edit it.
489   GURL abort_url(test_server()->GetURL("nocontent"));
490   {
491     content::WindowedNotificationObserver stop_observer(
492         content::NOTIFICATION_LOAD_STOP,
493         content::Source<NavigationController>(
494             &web_contents->GetController()));
495     browser()->OpenURL(OpenURLParams(abort_url, Referrer(), CURRENT_TAB,
496                                      content::PAGE_TRANSITION_TYPED, false));
497     stop_observer.Wait();
498     EXPECT_TRUE(web_contents->GetController().GetPendingEntry());
499     EXPECT_EQ(abort_url, web_contents->GetVisibleURL());
500   }
501
502   // Navigate to a real URL.
503   GURL real_url(test_server()->GetURL("title1.html"));
504   ui_test_utils::NavigateToURL(browser(), real_url);
505   EXPECT_EQ(real_url, web_contents->GetVisibleURL());
506
507   // Now navigating to a 204 URL should clear the pending entry.
508   {
509     content::WindowedNotificationObserver stop_observer(
510         content::NOTIFICATION_LOAD_STOP,
511         content::Source<NavigationController>(
512             &web_contents->GetController()));
513     browser()->OpenURL(OpenURLParams(abort_url, Referrer(), CURRENT_TAB,
514                                      content::PAGE_TRANSITION_TYPED, false));
515     stop_observer.Wait();
516     EXPECT_FALSE(web_contents->GetController().GetPendingEntry());
517     EXPECT_EQ(real_url, web_contents->GetVisibleURL());
518   }
519 }
520
521 // Test for crbug.com/297289.  Ensure that modal dialogs are closed when a
522 // cross-process navigation is ready to commit.
523 IN_PROC_BROWSER_TEST_F(BrowserTest, CrossProcessNavCancelsDialogs) {
524   ASSERT_TRUE(test_server()->Start());
525   host_resolver()->AddRule("www.example.com", "127.0.0.1");
526   GURL url(test_server()->GetURL("empty.html"));
527   ui_test_utils::NavigateToURL(browser(), url);
528
529   // Test this with multiple alert dialogs to ensure that we can navigate away
530   // even if the renderer tries to synchronously create more.
531   // See http://crbug.com/312490.
532   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
533   contents->GetMainFrame()->ExecuteJavaScript(
534       ASCIIToUTF16("alert('one'); alert('two');"));
535   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
536   EXPECT_TRUE(alert->IsValid());
537   AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
538   EXPECT_TRUE(dialog_queue->HasActiveDialog());
539
540   // A cross-site navigation should force the dialog to close.
541   GURL url2("http://www.example.com/empty.html");
542   ui_test_utils::NavigateToURL(browser(), url2);
543   EXPECT_FALSE(dialog_queue->HasActiveDialog());
544
545   // Make sure input events still work in the renderer process.
546   EXPECT_FALSE(contents->GetRenderProcessHost()->IgnoreInputEvents());
547 }
548
549 // Make sure that dialogs are closed after a renderer process dies, and that
550 // subsequent navigations work.  See http://crbug/com/343265.
551 IN_PROC_BROWSER_TEST_F(BrowserTest, SadTabCancelsDialogs) {
552   ASSERT_TRUE(test_server()->Start());
553   host_resolver()->AddRule("www.example.com", "127.0.0.1");
554   GURL beforeunload_url(test_server()->GetURL("files/beforeunload.html"));
555   ui_test_utils::NavigateToURL(browser(), beforeunload_url);
556
557   // Start a navigation to trigger the beforeunload dialog.
558   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
559   contents->GetMainFrame()->ExecuteJavaScript(
560       ASCIIToUTF16("window.location.href = 'data:text/html,foo'"));
561   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
562   EXPECT_TRUE(alert->IsValid());
563   AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
564   EXPECT_TRUE(dialog_queue->HasActiveDialog());
565
566   // Crash the renderer process and ensure the dialog is gone.
567   content::RenderProcessHost* child_process = contents->GetRenderProcessHost();
568   content::RenderProcessHostWatcher crash_observer(
569       child_process,
570       content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
571   base::KillProcess(child_process->GetHandle(), 0, false);
572   crash_observer.Wait();
573   EXPECT_FALSE(dialog_queue->HasActiveDialog());
574
575   // Make sure subsequent navigations work.
576   GURL url2("http://www.example.com/files/empty.html");
577   ui_test_utils::NavigateToURL(browser(), url2);
578 }
579
580 // Make sure that dialogs opened by subframes are closed when the process dies.
581 // See http://crbug.com/366510.
582 IN_PROC_BROWSER_TEST_F(BrowserTest, SadTabCancelsSubframeDialogs) {
583   // Navigate to an iframe that opens an alert dialog.
584   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
585   contents->GetMainFrame()->ExecuteJavaScript(
586       ASCIIToUTF16("window.location.href = 'data:text/html,"
587                    "<iframe srcdoc=\"<script>alert(1)</script>\">'"));
588   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
589   EXPECT_TRUE(alert->IsValid());
590   AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
591   EXPECT_TRUE(dialog_queue->HasActiveDialog());
592
593   // Crash the renderer process and ensure the dialog is gone.
594   content::RenderProcessHost* child_process = contents->GetRenderProcessHost();
595   content::RenderProcessHostWatcher crash_observer(
596       child_process,
597       content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
598   base::KillProcess(child_process->GetHandle(), 0, false);
599   crash_observer.Wait();
600   EXPECT_FALSE(dialog_queue->HasActiveDialog());
601
602   // Make sure subsequent navigations work.
603   GURL url2("data:text/html,foo");
604   ui_test_utils::NavigateToURL(browser(), url2);
605 }
606
607 // Test for crbug.com/22004.  Reloading a page with a before unload handler and
608 // then canceling the dialog should not leave the throbber spinning.
609 IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {
610   GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
611   ui_test_utils::NavigateToURL(browser(), url);
612
613   // Navigate to another page, but click cancel in the dialog.  Make sure that
614   // the throbber stops spinning.
615   chrome::Reload(browser(), CURRENT_TAB);
616   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
617   alert->CloseModalDialog();
618   EXPECT_FALSE(
619       browser()->tab_strip_model()->GetActiveWebContents()->IsLoading());
620
621   // Clear the beforeunload handler so the test can easily exit.
622   browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
623       ExecuteJavaScript(ASCIIToUTF16("onbeforeunload=null;"));
624 }
625
626 class RedirectObserver : public content::WebContentsObserver {
627  public:
628   explicit RedirectObserver(content::WebContents* web_contents)
629       : WebContentsObserver(web_contents) {
630   }
631
632   virtual void DidNavigateAnyFrame(
633       const content::LoadCommittedDetails& details,
634       const content::FrameNavigateParams& params) OVERRIDE {
635     params_ = params;
636   }
637
638   virtual void WebContentsDestroyed() OVERRIDE {
639     // Make sure we don't close the tab while the observer is in scope.
640     // See http://crbug.com/314036.
641     FAIL() << "WebContents closed during navigation (http://crbug.com/314036).";
642   }
643
644   const content::FrameNavigateParams& params() const {
645     return params_;
646   }
647
648  private:
649   content::FrameNavigateParams params_;
650
651   DISALLOW_COPY_AND_ASSIGN(RedirectObserver);
652 };
653
654 // Ensure that a transferred cross-process navigation does not generate
655 // DidStopLoading events until the navigation commits.  If it did, then
656 // ui_test_utils::NavigateToURL would proceed before the URL had committed.
657 // http://crbug.com/243957.
658 IN_PROC_BROWSER_TEST_F(BrowserTest, NoStopDuringTransferUntilCommit) {
659   // Create HTTP and HTTPS servers for a cross-site transition.
660   ASSERT_TRUE(test_server()->Start());
661   net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
662                                            net::SpawnedTestServer::kLocalhost,
663                                            base::FilePath(kDocRoot));
664   ASSERT_TRUE(https_test_server.Start());
665
666   // Temporarily replace ContentBrowserClient with one that will cause a
667   // process swap on all redirects to HTTPS URLs.
668   TransferHttpsRedirectsContentBrowserClient new_client;
669   content::ContentBrowserClient* old_client =
670       SetBrowserClientForTesting(&new_client);
671
672   GURL init_url(test_server()->GetURL("files/title1.html"));
673   ui_test_utils::NavigateToURL(browser(), init_url);
674
675   // Navigate to a same-site page that redirects, causing a transfer.
676   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
677
678   // Create a RedirectObserver that goes away before we close the tab.
679   {
680     RedirectObserver redirect_observer(contents);
681     GURL dest_url(https_test_server.GetURL("files/title2.html"));
682     GURL redirect_url(test_server()->GetURL("server-redirect?" +
683         dest_url.spec()));
684     ui_test_utils::NavigateToURL(browser(), redirect_url);
685
686     // We should immediately see the new committed entry.
687     EXPECT_FALSE(contents->GetController().GetPendingEntry());
688     EXPECT_EQ(dest_url,
689               contents->GetController().GetLastCommittedEntry()->GetURL());
690
691     // We should keep track of the original request URL, redirect chain, and
692     // page transition type during a transfer, since these are necessary for
693     // history autocomplete to work.
694     EXPECT_EQ(redirect_url, contents->GetController().GetLastCommittedEntry()->
695                   GetOriginalRequestURL());
696     EXPECT_EQ(2U, redirect_observer.params().redirects.size());
697     EXPECT_EQ(redirect_url, redirect_observer.params().redirects.at(0));
698     EXPECT_EQ(dest_url, redirect_observer.params().redirects.at(1));
699     EXPECT_TRUE(PageTransitionCoreTypeIs(redirect_observer.params().transition,
700                                          content::PAGE_TRANSITION_TYPED));
701   }
702
703   // Restore previous browser client.
704   SetBrowserClientForTesting(old_client);
705 }
706
707 // Tests that a cross-process redirect will only cause the beforeunload
708 // handler to run once.
709 IN_PROC_BROWSER_TEST_F(BrowserTest, SingleBeforeUnloadAfterRedirect) {
710   // Create HTTP and HTTPS servers for a cross-site transition.
711   ASSERT_TRUE(test_server()->Start());
712   net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
713                                            net::SpawnedTestServer::kLocalhost,
714                                            base::FilePath(kDocRoot));
715   ASSERT_TRUE(https_test_server.Start());
716
717   // Temporarily replace ContentBrowserClient with one that will cause a
718   // process swap on all redirects to HTTPS URLs.
719   TransferHttpsRedirectsContentBrowserClient new_client;
720   content::ContentBrowserClient* old_client =
721       SetBrowserClientForTesting(&new_client);
722
723   // Navigate to a page with a beforeunload handler.
724   GURL url(test_server()->GetURL("files/beforeunload.html"));
725   ui_test_utils::NavigateToURL(browser(), url);
726
727   // Navigate to a URL that redirects to another process and approve the
728   // beforeunload dialog that pops up.
729   content::WindowedNotificationObserver nav_observer(
730       content::NOTIFICATION_NAV_ENTRY_COMMITTED,
731       content::NotificationService::AllSources());
732   GURL https_url(https_test_server.GetURL("files/title1.html"));
733   GURL redirect_url(test_server()->GetURL("server-redirect?" +
734       https_url.spec()));
735   browser()->OpenURL(OpenURLParams(redirect_url, Referrer(), CURRENT_TAB,
736                                    content::PAGE_TRANSITION_TYPED, false));
737   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
738   EXPECT_TRUE(
739       static_cast<JavaScriptAppModalDialog*>(alert)->is_before_unload_dialog());
740   alert->native_dialog()->AcceptAppModalDialog();
741   nav_observer.Wait();
742
743   // Restore previous browser client.
744   SetBrowserClientForTesting(old_client);
745 }
746
747 // Test for crbug.com/80401.  Canceling a before unload dialog should reset
748 // the URL to the previous page's URL.
749 IN_PROC_BROWSER_TEST_F(BrowserTest, CancelBeforeUnloadResetsURL) {
750   GURL url(ui_test_utils::GetTestUrl(base::FilePath(
751       base::FilePath::kCurrentDirectory), base::FilePath(kBeforeUnloadFile)));
752   ui_test_utils::NavigateToURL(browser(), url);
753
754   // Navigate to a page that triggers a cross-site transition.
755   ASSERT_TRUE(test_server()->Start());
756   GURL url2(test_server()->GetURL("files/title1.html"));
757   browser()->OpenURL(OpenURLParams(
758       url2, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
759
760   content::WindowedNotificationObserver host_destroyed_observer(
761       content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
762       content::NotificationService::AllSources());
763
764   // Cancel the dialog.
765   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
766   alert->CloseModalDialog();
767   EXPECT_FALSE(
768       browser()->tab_strip_model()->GetActiveWebContents()->IsLoading());
769
770   // Verify there are no pending history items after the dialog is cancelled.
771   // (see crbug.com/93858)
772   NavigationEntry* entry = browser()->tab_strip_model()->
773       GetActiveWebContents()->GetController().GetPendingEntry();
774   EXPECT_EQ(NULL, entry);
775
776   // Wait for the ShouldClose_ACK to arrive.  We can detect it by waiting for
777   // the pending RVH to be destroyed.
778   host_destroyed_observer.Wait();
779   EXPECT_EQ(url, browser()->toolbar_model()->GetURL());
780
781   // Clear the beforeunload handler so the test can easily exit.
782   browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
783       ExecuteJavaScript(ASCIIToUTF16("onbeforeunload=null;"));
784 }
785
786 // Crashy on mac.  http://crbug.com/38522  Crashy on win too (after 3 years).
787 #if defined(OS_MACOSX) || defined(OS_WIN)
788 #define MAYBE_SingleBeforeUnloadAfterWindowClose \
789         DISABLED_SingleBeforeUnloadAfterWindowClose
790 #else
791 #define MAYBE_SingleBeforeUnloadAfterWindowClose \
792         SingleBeforeUnloadAfterWindowClose
793 #endif
794
795 // Test for crbug.com/11647.  A page closed with window.close() should not have
796 // two beforeunload dialogs shown.
797 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_SingleBeforeUnloadAfterWindowClose) {
798   browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
799       ExecuteJavaScript(ASCIIToUTF16(kOpenNewBeforeUnloadPage));
800
801   // Close the new window with JavaScript, which should show a single
802   // beforeunload dialog.  Then show another alert, to make it easy to verify
803   // that a second beforeunload dialog isn't shown.
804   browser()->tab_strip_model()->GetWebContentsAt(0)->GetMainFrame()->
805       ExecuteJavaScript(ASCIIToUTF16("w.close(); alert('bar');"));
806   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
807   alert->native_dialog()->AcceptAppModalDialog();
808
809   alert = ui_test_utils::WaitForAppModalDialog();
810   EXPECT_FALSE(static_cast<JavaScriptAppModalDialog*>(alert)->
811                    is_before_unload_dialog());
812   alert->native_dialog()->AcceptAppModalDialog();
813 }
814
815 // BrowserTest.BeforeUnloadVsBeforeReload times out on Windows.
816 // http://crbug.com/130411
817 #if defined(OS_WIN)
818 #define MAYBE_BeforeUnloadVsBeforeReload DISABLED_BeforeUnloadVsBeforeReload
819 #else
820 #define MAYBE_BeforeUnloadVsBeforeReload BeforeUnloadVsBeforeReload
821 #endif
822
823 // Test that when a page has an onunload handler, reloading a page shows a
824 // different dialog than navigating to a different page.
825 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_BeforeUnloadVsBeforeReload) {
826   GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
827   ui_test_utils::NavigateToURL(browser(), url);
828
829   // Reload the page, and check that we get a "before reload" dialog.
830   chrome::Reload(browser(), CURRENT_TAB);
831   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
832   EXPECT_TRUE(static_cast<JavaScriptAppModalDialog*>(alert)->is_reload());
833
834   // Cancel the reload.
835   alert->native_dialog()->CancelAppModalDialog();
836
837   // Navigate to another url, and check that we get a "before unload" dialog.
838   GURL url2(url::kAboutBlankURL);
839   browser()->OpenURL(OpenURLParams(
840       url2, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));
841
842   alert = ui_test_utils::WaitForAppModalDialog();
843   EXPECT_FALSE(static_cast<JavaScriptAppModalDialog*>(alert)->is_reload());
844
845   // Accept the navigation so we end up on a page without a beforeunload hook.
846   alert->native_dialog()->AcceptAppModalDialog();
847 }
848
849 // BeforeUnloadAtQuitWithTwoWindows is a regression test for
850 // http://crbug.com/11842. It opens two windows, one of which has a
851 // beforeunload handler and attempts to exit cleanly.
852 class BeforeUnloadAtQuitWithTwoWindows : public InProcessBrowserTest {
853  public:
854   // This test is for testing a specific shutdown behavior. This mimics what
855   // happens in InProcessBrowserTest::RunTestOnMainThread and QuitBrowsers, but
856   // ensures that it happens through the single IDC_EXIT of the test.
857   virtual void TearDownOnMainThread() OVERRIDE {
858     // Cycle both the MessageLoop and the Cocoa runloop twice to flush out any
859     // Chrome work that generates Cocoa work. Do this twice since there are two
860     // Browsers that must be closed.
861     CycleRunLoops();
862     CycleRunLoops();
863
864     // Run the application event loop to completion, which will cycle the
865     // native MessagePump on all platforms.
866     base::MessageLoop::current()->PostTask(FROM_HERE,
867                                            base::MessageLoop::QuitClosure());
868     base::MessageLoop::current()->Run();
869
870     // Take care of any remaining Cocoa work.
871     CycleRunLoops();
872
873     // At this point, quit should be for real now.
874     ASSERT_EQ(0u, chrome::GetTotalBrowserCount());
875   }
876
877   // A helper function that cycles the MessageLoop, and on Mac, the Cocoa run
878   // loop. It also drains the NSAutoreleasePool.
879   void CycleRunLoops() {
880     content::RunAllPendingInMessageLoop();
881 #if defined(OS_MACOSX)
882     chrome::testing::NSRunLoopRunAllPending();
883     AutoreleasePool()->Recycle();
884 #endif
885   }
886 };
887
888 // Disabled, http://crbug.com/159214 .
889 IN_PROC_BROWSER_TEST_F(BeforeUnloadAtQuitWithTwoWindows,
890                        DISABLED_IfThisTestTimesOutItIndicatesFAILURE) {
891   // In the first browser, set up a page that has a beforeunload handler.
892   GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
893   ui_test_utils::NavigateToURL(browser(), url);
894
895   // Open a second browser window at about:blank.
896   ui_test_utils::BrowserAddedObserver browser_added_observer;
897   chrome::NewEmptyWindow(browser()->profile(), chrome::GetActiveDesktop());
898   Browser* second_window = browser_added_observer.WaitForSingleNewBrowser();
899   ui_test_utils::NavigateToURL(second_window, GURL(url::kAboutBlankURL));
900
901   // Tell the application to quit. IDC_EXIT calls AttemptUserExit, which on
902   // everything but ChromeOS allows unload handlers to block exit. On that
903   // platform, though, it exits unconditionally. See the comment and bug ID
904   // in AttemptUserExit() in application_lifetime.cc.
905 #if defined(OS_CHROMEOS)
906   chrome::AttemptExit();
907 #else
908   chrome::ExecuteCommand(second_window, IDC_EXIT);
909 #endif
910
911   // The beforeunload handler will run at exit, ensure it does, and then accept
912   // it to allow shutdown to proceed.
913   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
914   ASSERT_TRUE(alert);
915   EXPECT_TRUE(
916       static_cast<JavaScriptAppModalDialog*>(alert)->is_before_unload_dialog());
917   alert->native_dialog()->AcceptAppModalDialog();
918
919   // But wait there's more! If this test times out, it likely means that the
920   // browser has not been able to quit correctly, indicating there's a
921   // regression of the bug noted above.
922 }
923
924 // Test that scripts can fork a new renderer process for a cross-site popup,
925 // based on http://www.google.com/chrome/intl/en/webmasters-faq.html#newtab.
926 // The script must open a new tab, set its window.opener to null, and navigate
927 // it to a cross-site URL.  It should also work for meta-refreshes.
928 // See http://crbug.com/93517.
929 IN_PROC_BROWSER_TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
930   CommandLine::ForCurrentProcess()->AppendSwitch(
931       switches::kDisablePopupBlocking);
932
933   // Create http and https servers for a cross-site transition.
934   ASSERT_TRUE(test_server()->Start());
935   net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
936                                            net::SpawnedTestServer::kLocalhost,
937                                            base::FilePath(kDocRoot));
938   ASSERT_TRUE(https_test_server.Start());
939   GURL http_url(test_server()->GetURL("files/title1.html"));
940   GURL https_url(https_test_server.GetURL(std::string()));
941
942   // Start with an http URL.
943   ui_test_utils::NavigateToURL(browser(), http_url);
944   WebContents* oldtab = browser()->tab_strip_model()->GetActiveWebContents();
945   content::RenderProcessHost* process = oldtab->GetRenderProcessHost();
946
947   // Now open a tab to a blank page, set its opener to null, and redirect it
948   // cross-site.
949   std::string redirect_popup = "w=window.open();";
950   redirect_popup += "w.opener=null;";
951   redirect_popup += "w.document.location=\"";
952   redirect_popup += https_url.spec();
953   redirect_popup += "\";";
954
955   content::WindowedNotificationObserver popup_observer(
956       chrome::NOTIFICATION_TAB_ADDED,
957       content::NotificationService::AllSources());
958   content::WindowedNotificationObserver nav_observer(
959       content::NOTIFICATION_NAV_ENTRY_COMMITTED,
960       content::NotificationService::AllSources());
961   oldtab->GetMainFrame()->ExecuteJavaScript(ASCIIToUTF16(redirect_popup));
962
963   // Wait for popup window to appear and finish navigating.
964   popup_observer.Wait();
965   ASSERT_EQ(2, browser()->tab_strip_model()->count());
966   WebContents* newtab = browser()->tab_strip_model()->GetActiveWebContents();
967   EXPECT_TRUE(newtab);
968   EXPECT_NE(oldtab, newtab);
969   nav_observer.Wait();
970   ASSERT_TRUE(newtab->GetController().GetLastCommittedEntry());
971   EXPECT_EQ(https_url.spec(),
972             newtab->GetController().GetLastCommittedEntry()->GetURL().spec());
973
974   // Popup window should not be in the opener's process.
975   content::RenderProcessHost* popup_process =
976       newtab->GetRenderProcessHost();
977   EXPECT_NE(process, popup_process);
978
979   // Now open a tab to a blank page, set its opener to null, and use a
980   // meta-refresh to navigate it instead.
981   std::string refresh_popup = "w=window.open();";
982   refresh_popup += "w.opener=null;";
983   refresh_popup += "w.document.write(";
984   refresh_popup += "'<META HTTP-EQUIV=\"refresh\" content=\"0; url=";
985   refresh_popup += https_url.spec();
986   refresh_popup += "\">');w.document.close();";
987
988   content::WindowedNotificationObserver popup_observer2(
989       chrome::NOTIFICATION_TAB_ADDED,
990       content::NotificationService::AllSources());
991   content::WindowedNotificationObserver nav_observer2(
992       content::NOTIFICATION_NAV_ENTRY_COMMITTED,
993       content::NotificationService::AllSources());
994   oldtab->GetMainFrame()->ExecuteJavaScript(ASCIIToUTF16(refresh_popup));
995
996   // Wait for popup window to appear and finish navigating.
997   popup_observer2.Wait();
998   ASSERT_EQ(3, browser()->tab_strip_model()->count());
999   WebContents* newtab2 = browser()->tab_strip_model()->GetActiveWebContents();
1000   EXPECT_TRUE(newtab2);
1001   EXPECT_NE(oldtab, newtab2);
1002   nav_observer2.Wait();
1003   ASSERT_TRUE(newtab2->GetController().GetLastCommittedEntry());
1004   EXPECT_EQ(https_url.spec(),
1005             newtab2->GetController().GetLastCommittedEntry()->GetURL().spec());
1006
1007   // This popup window should also not be in the opener's process.
1008   content::RenderProcessHost* popup_process2 =
1009       newtab2->GetRenderProcessHost();
1010   EXPECT_NE(process, popup_process2);
1011 }
1012
1013 // Tests that other popup navigations that do not follow the steps at
1014 // http://www.google.com/chrome/intl/en/webmasters-faq.html#newtab will not
1015 // fork a new renderer process.
1016 IN_PROC_BROWSER_TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
1017   CommandLine::ForCurrentProcess()->AppendSwitch(
1018       switches::kDisablePopupBlocking);
1019
1020   // Create http and https servers for a cross-site transition.
1021   ASSERT_TRUE(test_server()->Start());
1022   net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
1023                                            net::SpawnedTestServer::kLocalhost,
1024                                            base::FilePath(kDocRoot));
1025   ASSERT_TRUE(https_test_server.Start());
1026   GURL http_url(test_server()->GetURL("files/title1.html"));
1027   GURL https_url(https_test_server.GetURL(std::string()));
1028
1029   // Start with an http URL.
1030   ui_test_utils::NavigateToURL(browser(), http_url);
1031   WebContents* oldtab = browser()->tab_strip_model()->GetActiveWebContents();
1032   content::RenderProcessHost* process = oldtab->GetRenderProcessHost();
1033
1034   // Now open a tab to a blank page, set its opener to null, and redirect it
1035   // cross-site.
1036   std::string dont_fork_popup = "w=window.open();";
1037   dont_fork_popup += "w.document.location=\"";
1038   dont_fork_popup += https_url.spec();
1039   dont_fork_popup += "\";";
1040
1041   content::WindowedNotificationObserver popup_observer(
1042       chrome::NOTIFICATION_TAB_ADDED,
1043       content::NotificationService::AllSources());
1044   content::WindowedNotificationObserver nav_observer(
1045       content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1046       content::NotificationService::AllSources());
1047   oldtab->GetMainFrame()->ExecuteJavaScript(ASCIIToUTF16(dont_fork_popup));
1048
1049   // Wait for popup window to appear and finish navigating.
1050   popup_observer.Wait();
1051   ASSERT_EQ(2, browser()->tab_strip_model()->count());
1052   WebContents* newtab = browser()->tab_strip_model()->GetActiveWebContents();
1053   EXPECT_TRUE(newtab);
1054   EXPECT_NE(oldtab, newtab);
1055   nav_observer.Wait();
1056   ASSERT_TRUE(newtab->GetController().GetLastCommittedEntry());
1057   EXPECT_EQ(https_url.spec(),
1058             newtab->GetController().GetLastCommittedEntry()->GetURL().spec());
1059
1060   // Popup window should still be in the opener's process.
1061   content::RenderProcessHost* popup_process =
1062       newtab->GetRenderProcessHost();
1063   EXPECT_EQ(process, popup_process);
1064
1065   // Same thing if the current tab tries to navigate itself.
1066   std::string navigate_str = "document.location=\"";
1067   navigate_str += https_url.spec();
1068   navigate_str += "\";";
1069
1070   content::WindowedNotificationObserver nav_observer2(
1071         content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1072         content::NotificationService::AllSources());
1073   oldtab->GetMainFrame()->ExecuteJavaScript(ASCIIToUTF16(navigate_str));
1074   nav_observer2.Wait();
1075   ASSERT_TRUE(oldtab->GetController().GetLastCommittedEntry());
1076   EXPECT_EQ(https_url.spec(),
1077             oldtab->GetController().GetLastCommittedEntry()->GetURL().spec());
1078
1079   // Original window should still be in the original process.
1080   content::RenderProcessHost* new_process = newtab->GetRenderProcessHost();
1081   EXPECT_EQ(process, new_process);
1082 }
1083
1084 // Test that get_process_idle_time() returns reasonable values when compared
1085 // with time deltas measured locally.
1086 IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {
1087   base::TimeTicks start = base::TimeTicks::Now();
1088   ui_test_utils::NavigateToURL(
1089       browser(), ui_test_utils::GetTestUrl(
1090                      base::FilePath(base::FilePath::kCurrentDirectory),
1091                      base::FilePath(kTitle1File)));
1092   content::RenderProcessHost::iterator it(
1093       content::RenderProcessHost::AllHostsIterator());
1094   for (; !it.IsAtEnd(); it.Advance()) {
1095     base::TimeDelta renderer_td =
1096         it.GetCurrentValue()->GetChildProcessIdleTime();
1097     base::TimeDelta browser_td = base::TimeTicks::Now() - start;
1098     EXPECT_TRUE(browser_td >= renderer_td);
1099   }
1100 }
1101
1102 // Test IDC_CREATE_SHORTCUTS command is enabled for url scheme file, ftp, http
1103 // and https and disabled for chrome://, about:// etc.
1104 // TODO(pinkerton): Disable app-mode in the model until we implement it
1105 // on the Mac. http://crbug.com/13148
1106 #if !defined(OS_MACOSX)
1107 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutFile) {
1108   CommandUpdater* command_updater =
1109       browser()->command_controller()->command_updater();
1110
1111   static const base::FilePath::CharType* kEmptyFile =
1112       FILE_PATH_LITERAL("empty.html");
1113   GURL file_url(ui_test_utils::GetTestUrl(base::FilePath(
1114       base::FilePath::kCurrentDirectory), base::FilePath(kEmptyFile)));
1115   ASSERT_TRUE(file_url.SchemeIs(url::kFileScheme));
1116   ui_test_utils::NavigateToURL(browser(), file_url);
1117   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1118 }
1119
1120 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutHttp) {
1121   CommandUpdater* command_updater =
1122       browser()->command_controller()->command_updater();
1123
1124   ASSERT_TRUE(test_server()->Start());
1125   GURL http_url(test_server()->GetURL(std::string()));
1126   ASSERT_TRUE(http_url.SchemeIs(url::kHttpScheme));
1127   ui_test_utils::NavigateToURL(browser(), http_url);
1128   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1129 }
1130
1131 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutHttps) {
1132   CommandUpdater* command_updater =
1133       browser()->command_controller()->command_updater();
1134
1135   net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS,
1136                                      net::SpawnedTestServer::kLocalhost,
1137                                      base::FilePath(kDocRoot));
1138   ASSERT_TRUE(test_server.Start());
1139   GURL https_url(test_server.GetURL("/"));
1140   ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme));
1141   ui_test_utils::NavigateToURL(browser(), https_url);
1142   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1143 }
1144
1145 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutFtp) {
1146   CommandUpdater* command_updater =
1147       browser()->command_controller()->command_updater();
1148
1149   net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_FTP,
1150                                      net::SpawnedTestServer::kLocalhost,
1151                                      base::FilePath(kDocRoot));
1152   ASSERT_TRUE(test_server.Start());
1153   GURL ftp_url(test_server.GetURL(std::string()));
1154   ASSERT_TRUE(ftp_url.SchemeIs(url::kFtpScheme));
1155   ui_test_utils::NavigateToURL(browser(), ftp_url);
1156   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1157 }
1158
1159 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutInvalid) {
1160   CommandUpdater* command_updater =
1161       browser()->command_controller()->command_updater();
1162
1163   // Urls that should not have shortcuts.
1164   GURL new_tab_url(chrome::kChromeUINewTabURL);
1165   ui_test_utils::NavigateToURL(browser(), new_tab_url);
1166   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1167
1168   GURL history_url(chrome::kChromeUIHistoryURL);
1169   ui_test_utils::NavigateToURL(browser(), history_url);
1170   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1171
1172   GURL downloads_url(chrome::kChromeUIDownloadsURL);
1173   ui_test_utils::NavigateToURL(browser(), downloads_url);
1174   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1175
1176   GURL blank_url(url::kAboutBlankURL);
1177   ui_test_utils::NavigateToURL(browser(), blank_url);
1178   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1179 }
1180
1181 // Change a tab into an application window.
1182 // DISABLED: http://crbug.com/72310
1183 IN_PROC_BROWSER_TEST_F(BrowserTest, DISABLED_ConvertTabToAppShortcut) {
1184   ASSERT_TRUE(test_server()->Start());
1185   GURL http_url(test_server()->GetURL(std::string()));
1186   ASSERT_TRUE(http_url.SchemeIs(url::kHttpScheme));
1187
1188   ASSERT_EQ(1, browser()->tab_strip_model()->count());
1189   WebContents* initial_tab = browser()->tab_strip_model()->GetWebContentsAt(0);
1190   WebContents* app_tab = chrome::AddSelectedTabWithURL(
1191       browser(), http_url, content::PAGE_TRANSITION_TYPED);
1192   ASSERT_EQ(2, browser()->tab_strip_model()->count());
1193   ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile(),
1194                                         browser()->host_desktop_type()));
1195
1196   // Normal tabs should accept load drops.
1197   EXPECT_TRUE(initial_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1198   EXPECT_TRUE(app_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1199
1200   // Turn |app_tab| into a tab in an app panel.
1201   chrome::ConvertTabToAppWindow(browser(), app_tab);
1202
1203   // The launch should have created a new browser.
1204   ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1205                                         browser()->host_desktop_type()));
1206
1207   // Find the new browser.
1208   Browser* app_browser = NULL;
1209   for (chrome::BrowserIterator it; !it.done() && !app_browser; it.Next()) {
1210     if (*it != browser())
1211       app_browser = *it;
1212   }
1213   ASSERT_TRUE(app_browser);
1214
1215   // Check that the tab contents is in the new browser, and not in the old.
1216   ASSERT_EQ(1, browser()->tab_strip_model()->count());
1217   ASSERT_EQ(initial_tab, browser()->tab_strip_model()->GetWebContentsAt(0));
1218
1219   // Check that the appliaction browser has a single tab, and that tab contains
1220   // the content that we app-ified.
1221   ASSERT_EQ(1, app_browser->tab_strip_model()->count());
1222   ASSERT_EQ(app_tab, app_browser->tab_strip_model()->GetWebContentsAt(0));
1223
1224   // Normal tabs should accept load drops.
1225   EXPECT_TRUE(initial_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1226
1227   // The tab in an app window should not.
1228   EXPECT_FALSE(app_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1229 }
1230
1231 #endif  // !defined(OS_MACOSX)
1232
1233 // Test RenderView correctly send back favicon url for web page that redirects
1234 // to an anchor in javascript body.onload handler.
1235 IN_PROC_BROWSER_TEST_F(BrowserTest,
1236                        DISABLED_FaviconOfOnloadRedirectToAnchorPage) {
1237   ASSERT_TRUE(test_server()->Start());
1238   GURL url(test_server()->GetURL("files/onload_redirect_to_anchor.html"));
1239   GURL expected_favicon_url(test_server()->GetURL("files/test.png"));
1240
1241   ui_test_utils::NavigateToURL(browser(), url);
1242
1243   NavigationEntry* entry = browser()->tab_strip_model()->
1244       GetActiveWebContents()->GetController().GetLastCommittedEntry();
1245   EXPECT_EQ(expected_favicon_url.spec(), entry->GetFavicon().url.spec());
1246 }
1247
1248 #if defined(OS_MACOSX) || defined(OS_LINUX) || defined (OS_WIN)
1249 // http://crbug.com/83828. On Mac 10.6, the failure rate is 14%
1250 #define MAYBE_FaviconChange DISABLED_FaviconChange
1251 #else
1252 #define MAYBE_FaviconChange FaviconChange
1253 #endif
1254 // Test that an icon can be changed from JS.
1255 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_FaviconChange) {
1256   static const base::FilePath::CharType* kFile =
1257       FILE_PATH_LITERAL("onload_change_favicon.html");
1258   GURL file_url(ui_test_utils::GetTestUrl(base::FilePath(
1259       base::FilePath::kCurrentDirectory), base::FilePath(kFile)));
1260   ASSERT_TRUE(file_url.SchemeIs(url::kFileScheme));
1261   ui_test_utils::NavigateToURL(browser(), file_url);
1262
1263   NavigationEntry* entry = browser()->tab_strip_model()->
1264       GetActiveWebContents()->GetController().GetLastCommittedEntry();
1265   static const base::FilePath::CharType* kIcon =
1266       FILE_PATH_LITERAL("test1.png");
1267   GURL expected_favicon_url(ui_test_utils::GetTestUrl(base::FilePath(
1268       base::FilePath::kCurrentDirectory), base::FilePath(kIcon)));
1269   EXPECT_EQ(expected_favicon_url.spec(), entry->GetFavicon().url.spec());
1270 }
1271
1272 // http://crbug.com/172336
1273 #if defined(OS_WIN)
1274 #define MAYBE_TabClosingWhenRemovingExtension \
1275     DISABLED_TabClosingWhenRemovingExtension
1276 #else
1277 #define MAYBE_TabClosingWhenRemovingExtension TabClosingWhenRemovingExtension
1278 #endif
1279 // Makes sure TabClosing is sent when uninstalling an extension that is an app
1280 // tab.
1281 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_TabClosingWhenRemovingExtension) {
1282   ASSERT_TRUE(test_server()->Start());
1283   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1284   GURL url(test_server()->GetURL("empty.html"));
1285   TabStripModel* model = browser()->tab_strip_model();
1286
1287   ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1288
1289   const Extension* extension_app = GetExtension();
1290
1291   ui_test_utils::NavigateToURL(browser(), url);
1292
1293   WebContents* app_contents = WebContents::Create(
1294       WebContents::CreateParams(browser()->profile()));
1295   extensions::TabHelper::CreateForWebContents(app_contents);
1296   extensions::TabHelper* extensions_tab_helper =
1297       extensions::TabHelper::FromWebContents(app_contents);
1298   extensions_tab_helper->SetExtensionApp(extension_app);
1299
1300   model->AddWebContents(app_contents, 0, content::PageTransitionFromInt(0),
1301                         TabStripModel::ADD_NONE);
1302   model->SetTabPinned(0, true);
1303   ui_test_utils::NavigateToURL(browser(), url);
1304
1305   MockTabStripModelObserver observer;
1306   model->AddObserver(&observer);
1307
1308   // Uninstall the extension and make sure TabClosing is sent.
1309   ExtensionService* service = extensions::ExtensionSystem::Get(
1310       browser()->profile())->extension_service();
1311   service->UninstallExtension(GetExtension()->id(),
1312                               extensions::UNINSTALL_REASON_FOR_TESTING,
1313                               base::Bind(&base::DoNothing),
1314                               NULL);
1315   EXPECT_EQ(1, observer.closing_count());
1316
1317   model->RemoveObserver(&observer);
1318
1319   // There should only be one tab now.
1320   ASSERT_EQ(1, browser()->tab_strip_model()->count());
1321 }
1322
1323 #if !defined(OS_MACOSX)
1324 // Open with --app-id=<id>, and see that an app window opens.
1325 IN_PROC_BROWSER_TEST_F(BrowserTest, AppIdSwitch) {
1326   ASSERT_TRUE(test_server()->Start());
1327
1328   // Load an app.
1329   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1330   ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1331   const Extension* extension_app = GetExtension();
1332
1333   CommandLine command_line(CommandLine::NO_PROGRAM);
1334   command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
1335
1336   chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1337       chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1338   StartupBrowserCreatorImpl launch(base::FilePath(), command_line, first_run);
1339   ASSERT_TRUE(launch.OpenApplicationWindow(browser()->profile(), NULL));
1340
1341   // Check that the new browser has an app name.
1342   // The launch should have created a new browser.
1343   ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1344                                         browser()->host_desktop_type()));
1345
1346   // Find the new browser.
1347   Browser* new_browser = NULL;
1348   for (chrome::BrowserIterator it; !it.done() && !new_browser; it.Next()) {
1349     if (*it != browser())
1350       new_browser = *it;
1351   }
1352   ASSERT_TRUE(new_browser);
1353   ASSERT_TRUE(new_browser != browser());
1354
1355   // The browser's app_name should include the app's ID.
1356   ASSERT_NE(
1357       new_browser->app_name_.find(extension_app->id()),
1358       std::string::npos) << new_browser->app_name_;
1359 }
1360
1361 // Open an app window and the dev tools window and ensure that the location
1362 // bar settings are correct.
1363 IN_PROC_BROWSER_TEST_F(BrowserTest, ShouldShowLocationBar) {
1364   ASSERT_TRUE(test_server()->Start());
1365
1366   // Load an app.
1367   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1368   ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1369   const Extension* extension_app = GetExtension();
1370
1371   // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1372   WebContents* app_window =
1373       OpenApplication(AppLaunchParams(browser()->profile(),
1374                                       extension_app,
1375                                       extensions::LAUNCH_CONTAINER_WINDOW,
1376                                       NEW_WINDOW));
1377   ASSERT_TRUE(app_window);
1378
1379   DevToolsWindow* devtools_window =
1380       DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), false);
1381
1382   // The launch should have created a new app browser and a dev tools browser.
1383   ASSERT_EQ(3u,
1384             chrome::GetBrowserCount(browser()->profile(),
1385                                     browser()->host_desktop_type()));
1386
1387   // Find the new browsers.
1388   Browser* app_browser = NULL;
1389   Browser* dev_tools_browser = NULL;
1390   for (chrome::BrowserIterator it; !it.done(); it.Next()) {
1391     if (*it == browser()) {
1392       continue;
1393     } else if ((*it)->app_name() == DevToolsWindow::kDevToolsApp) {
1394       dev_tools_browser = *it;
1395     } else {
1396       app_browser = *it;
1397     }
1398   }
1399   ASSERT_TRUE(dev_tools_browser);
1400   ASSERT_TRUE(app_browser);
1401   ASSERT_TRUE(app_browser != browser());
1402
1403   EXPECT_FALSE(
1404       dev_tools_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR));
1405   EXPECT_FALSE(
1406       app_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR));
1407
1408   DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);
1409 }
1410 #endif
1411
1412 // Tests that the CLD (Compact Language Detection) works properly.
1413 IN_PROC_BROWSER_TEST_F(BrowserTest, PageLanguageDetection) {
1414   scoped_ptr<test::CldDataHarness> cld_data_harness =
1415       test::CreateCldDataHarness();
1416   ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init());
1417   ASSERT_TRUE(test_server()->Start());
1418
1419   translate::LanguageDetectionDetails details;
1420
1421   // Open a new tab with a page in English.
1422   AddTabAtIndex(0, GURL(test_server()->GetURL("files/english_page.html")),
1423                 content::PAGE_TRANSITION_TYPED);
1424
1425   WebContents* current_web_contents =
1426       browser()->tab_strip_model()->GetActiveWebContents();
1427   ChromeTranslateClient* chrome_translate_client =
1428       ChromeTranslateClient::FromWebContents(current_web_contents);
1429   content::Source<WebContents> source(current_web_contents);
1430
1431   ui_test_utils::WindowedNotificationObserverWithDetails<
1432       translate::LanguageDetectionDetails>
1433       en_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1434                                   source);
1435   EXPECT_EQ("",
1436             chrome_translate_client->GetLanguageState().original_language());
1437   en_language_detected_signal.Wait();
1438   EXPECT_TRUE(en_language_detected_signal.GetDetailsFor(
1439         source.map_key(), &details));
1440   EXPECT_EQ("en", details.adopted_language);
1441   EXPECT_EQ("en",
1442             chrome_translate_client->GetLanguageState().original_language());
1443
1444   // Now navigate to a page in French.
1445   ui_test_utils::WindowedNotificationObserverWithDetails<
1446       translate::LanguageDetectionDetails>
1447       fr_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1448                                   source);
1449   ui_test_utils::NavigateToURL(
1450       browser(), GURL(test_server()->GetURL("files/french_page.html")));
1451   fr_language_detected_signal.Wait();
1452   details.adopted_language.clear();
1453   EXPECT_TRUE(fr_language_detected_signal.GetDetailsFor(
1454         source.map_key(), &details));
1455   EXPECT_EQ("fr", details.adopted_language);
1456   EXPECT_EQ("fr",
1457             chrome_translate_client->GetLanguageState().original_language());
1458 }
1459
1460 // Chromeos defaults to restoring the last session, so this test isn't
1461 // applicable.
1462 #if !defined(OS_CHROMEOS)
1463 #if defined(OS_MACOSX)
1464 // Crashy, http://crbug.com/38522
1465 #define RestorePinnedTabs DISABLED_RestorePinnedTabs
1466 #endif
1467 // Makes sure pinned tabs are restored correctly on start.
1468 IN_PROC_BROWSER_TEST_F(BrowserTest, RestorePinnedTabs) {
1469   ASSERT_TRUE(test_server()->Start());
1470
1471   // Add an pinned app tab.
1472   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1473   GURL url(test_server()->GetURL("empty.html"));
1474   TabStripModel* model = browser()->tab_strip_model();
1475   ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1476   const Extension* extension_app = GetExtension();
1477   ui_test_utils::NavigateToURL(browser(), url);
1478   WebContents* app_contents = WebContents::Create(
1479       WebContents::CreateParams(browser()->profile()));
1480   extensions::TabHelper::CreateForWebContents(app_contents);
1481   extensions::TabHelper* extensions_tab_helper =
1482       extensions::TabHelper::FromWebContents(app_contents);
1483   extensions_tab_helper->SetExtensionApp(extension_app);
1484   model->AddWebContents(app_contents, 0, content::PageTransitionFromInt(0),
1485                         TabStripModel::ADD_NONE);
1486   model->SetTabPinned(0, true);
1487   ui_test_utils::NavigateToURL(browser(), url);
1488
1489   // Add a non pinned tab.
1490   chrome::NewTab(browser());
1491
1492   // Add a pinned non-app tab.
1493   chrome::NewTab(browser());
1494   ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1495   model->SetTabPinned(2, true);
1496
1497   // Write out the pinned tabs.
1498   PinnedTabCodec::WritePinnedTabs(browser()->profile());
1499
1500   // Simulate launching again.
1501   CommandLine dummy(CommandLine::NO_PROGRAM);
1502   chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1503       chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1504   StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1505   launch.profile_ = browser()->profile();
1506   launch.ProcessStartupURLs(std::vector<GURL>(),
1507                             browser()->host_desktop_type());
1508
1509   // The launch should have created a new browser.
1510   ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1511                                         browser()->host_desktop_type()));
1512
1513   // Find the new browser.
1514   Browser* new_browser = NULL;
1515   for (chrome::BrowserIterator it; !it.done() && !new_browser; it.Next()) {
1516     if (*it != browser())
1517       new_browser = *it;
1518   }
1519   ASSERT_TRUE(new_browser);
1520   ASSERT_TRUE(new_browser != browser());
1521
1522   // We should get back an additional tab for the app, and another for the
1523   // default home page.
1524   ASSERT_EQ(3, new_browser->tab_strip_model()->count());
1525
1526   // Make sure the state matches.
1527   TabStripModel* new_model = new_browser->tab_strip_model();
1528   EXPECT_TRUE(new_model->IsAppTab(0));
1529   EXPECT_FALSE(new_model->IsAppTab(1));
1530   EXPECT_FALSE(new_model->IsAppTab(2));
1531
1532   EXPECT_TRUE(new_model->IsTabPinned(0));
1533   EXPECT_TRUE(new_model->IsTabPinned(1));
1534   EXPECT_FALSE(new_model->IsTabPinned(2));
1535
1536   EXPECT_EQ(GURL(chrome::kChromeUINewTabURL),
1537             new_model->GetWebContentsAt(2)->GetURL());
1538
1539   EXPECT_TRUE(
1540       extensions::TabHelper::FromWebContents(
1541           new_model->GetWebContentsAt(0))->extension_app() == extension_app);
1542 }
1543 #endif  // !defined(OS_CHROMEOS)
1544
1545 // This test verifies we don't crash when closing the last window and the app
1546 // menu is showing.
1547 IN_PROC_BROWSER_TEST_F(BrowserTest, CloseWithAppMenuOpen) {
1548   if (browser_defaults::kBrowserAliveWithNoWindows)
1549     return;
1550
1551   // We need a message loop running for menus on windows.
1552   base::MessageLoop::current()->PostTask(
1553       FROM_HERE, base::Bind(&RunCloseWithAppMenuCallback, browser()));
1554 }
1555
1556 #if !defined(OS_MACOSX)
1557 IN_PROC_BROWSER_TEST_F(BrowserTest, OpenAppWindowLikeNtp) {
1558   ASSERT_TRUE(test_server()->Start());
1559
1560   // Load an app
1561   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1562   ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1563   const Extension* extension_app = GetExtension();
1564
1565   // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1566   WebContents* app_window = OpenApplication(
1567       AppLaunchParams(browser()->profile(), extension_app,
1568                       extensions::LAUNCH_CONTAINER_WINDOW, NEW_WINDOW));
1569   ASSERT_TRUE(app_window);
1570
1571   // Apps launched in a window from the NTP have an extensions tab helper but
1572   // do not have extension_app set in it.
1573   ASSERT_TRUE(extensions::TabHelper::FromWebContents(app_window));
1574   EXPECT_FALSE(
1575       extensions::TabHelper::FromWebContents(app_window)->extension_app());
1576   EXPECT_EQ(extensions::AppLaunchInfo::GetFullLaunchURL(extension_app),
1577             app_window->GetURL());
1578
1579   // The launch should have created a new browser.
1580   ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1581                                         browser()->host_desktop_type()));
1582
1583   // Find the new browser.
1584   Browser* new_browser = NULL;
1585   for (chrome::BrowserIterator it; !it.done() && !new_browser; it.Next()) {
1586     if (*it != browser())
1587       new_browser = *it;
1588   }
1589   ASSERT_TRUE(new_browser);
1590   ASSERT_TRUE(new_browser != browser());
1591
1592   EXPECT_TRUE(new_browser->is_app());
1593
1594   // The browser's app name should include the extension's id.
1595   std::string app_name = new_browser->app_name_;
1596   EXPECT_NE(app_name.find(extension_app->id()), std::string::npos)
1597       << "Name " << app_name << " should contain id "<< extension_app->id();
1598 }
1599 #endif  // !defined(OS_MACOSX)
1600
1601 // Makes sure the browser doesn't crash when
1602 // set_show_state(ui::SHOW_STATE_MAXIMIZED) has been invoked.
1603 IN_PROC_BROWSER_TEST_F(BrowserTest, StartMaximized) {
1604   Browser::Type types[] = { Browser::TYPE_TABBED, Browser::TYPE_POPUP };
1605   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(types); ++i) {
1606     Browser::CreateParams params(types[i], browser()->profile(),
1607                                  browser()->host_desktop_type());
1608     params.initial_show_state = ui::SHOW_STATE_MAXIMIZED;
1609     AddBlankTabAndShow(new Browser(params));
1610   }
1611 }
1612
1613 // Aura doesn't support minimized window. crbug.com/104571.
1614 #if defined(USE_AURA)
1615 #define MAYBE_StartMinimized DISABLED_StartMinimized
1616 #else
1617 #define MAYBE_StartMinimized StartMinimized
1618 #endif
1619 // Makes sure the browser doesn't crash when
1620 // set_show_state(ui::SHOW_STATE_MINIMIZED) has been invoked.
1621 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_StartMinimized) {
1622   Browser::Type types[] = { Browser::TYPE_TABBED, Browser::TYPE_POPUP };
1623   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(types); ++i) {
1624     Browser::CreateParams params(types[i], browser()->profile(),
1625                                  browser()->host_desktop_type());
1626     params.initial_show_state = ui::SHOW_STATE_MINIMIZED;
1627     AddBlankTabAndShow(new Browser(params));
1628   }
1629 }
1630
1631 // Makes sure the forward button is disabled immediately when navigating
1632 // forward to a slow-to-commit page.
1633 IN_PROC_BROWSER_TEST_F(BrowserTest, ForwardDisabledOnForward) {
1634   GURL blank_url(url::kAboutBlankURL);
1635   ui_test_utils::NavigateToURL(browser(), blank_url);
1636
1637   ui_test_utils::NavigateToURL(
1638       browser(), ui_test_utils::GetTestUrl(
1639                      base::FilePath(base::FilePath::kCurrentDirectory),
1640                      base::FilePath(kTitle1File)));
1641
1642   content::WindowedNotificationObserver back_nav_load_observer(
1643       content::NOTIFICATION_LOAD_STOP,
1644       content::Source<NavigationController>(
1645           &browser()->tab_strip_model()->GetActiveWebContents()->
1646               GetController()));
1647   chrome::GoBack(browser(), CURRENT_TAB);
1648   back_nav_load_observer.Wait();
1649   CommandUpdater* command_updater =
1650       browser()->command_controller()->command_updater();
1651   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_FORWARD));
1652
1653   content::WindowedNotificationObserver forward_nav_load_observer(
1654       content::NOTIFICATION_LOAD_STOP,
1655       content::Source<NavigationController>(
1656           &browser()->tab_strip_model()->GetActiveWebContents()->
1657               GetController()));
1658   chrome::GoForward(browser(), CURRENT_TAB);
1659   // This check will happen before the navigation completes, since the browser
1660   // won't process the renderer's response until the Wait() call below.
1661   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_FORWARD));
1662   forward_nav_load_observer.Wait();
1663 }
1664
1665 // Makes sure certain commands are disabled when Incognito mode is forced.
1666 IN_PROC_BROWSER_TEST_F(BrowserTest, DisableMenuItemsWhenIncognitoIsForced) {
1667   CommandUpdater* command_updater =
1668       browser()->command_controller()->command_updater();
1669   // At the beginning, all commands are enabled.
1670   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1671   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1672   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1673   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1674   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1675   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1676
1677   // Set Incognito to FORCED.
1678   IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1679                                       IncognitoModePrefs::FORCED);
1680   // Bookmarks & Settings commands should get disabled.
1681   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1682   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1683   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1684   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1685   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1686   // New Incognito Window command, however, should be enabled.
1687   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1688
1689   // Create a new browser.
1690   Browser* new_browser =
1691       new Browser(Browser::CreateParams(
1692           browser()->profile()->GetOffTheRecordProfile(),
1693           browser()->host_desktop_type()));
1694   CommandUpdater* new_command_updater =
1695       new_browser->command_controller()->command_updater();
1696   // It should have Bookmarks & Settings commands disabled by default.
1697   EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1698   EXPECT_FALSE(new_command_updater->IsCommandEnabled(
1699       IDC_SHOW_BOOKMARK_MANAGER));
1700   EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1701   EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1702   EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_OPTIONS));
1703   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1704 }
1705
1706 // Makes sure New Incognito Window command is disabled when Incognito mode is
1707 // not available.
1708 IN_PROC_BROWSER_TEST_F(BrowserTest,
1709                        NoNewIncognitoWindowWhenIncognitoIsDisabled) {
1710   CommandUpdater* command_updater =
1711       browser()->command_controller()->command_updater();
1712   // Set Incognito to DISABLED.
1713   IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1714                                       IncognitoModePrefs::DISABLED);
1715   // Make sure New Incognito Window command is disabled. All remaining commands
1716   // should be enabled.
1717   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1718   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1719   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1720   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1721   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1722   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1723
1724   // Create a new browser.
1725   Browser* new_browser =
1726       new Browser(Browser::CreateParams(browser()->profile(),
1727                                         browser()->host_desktop_type()));
1728   CommandUpdater* new_command_updater =
1729       new_browser->command_controller()->command_updater();
1730   EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1731   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1732   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1733   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1734   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1735   EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_OPTIONS));
1736 }
1737
1738 // Makes sure Extensions and Settings commands are disabled in certain
1739 // circumstances even though normally they should stay enabled.
1740 IN_PROC_BROWSER_TEST_F(BrowserTest,
1741                        DisableExtensionsAndSettingsWhenIncognitoIsDisabled) {
1742   CommandUpdater* command_updater =
1743       browser()->command_controller()->command_updater();
1744   // Disable extensions. This should disable Extensions menu.
1745   extensions::ExtensionSystem::Get(browser()->profile())->extension_service()->
1746       set_extensions_enabled(false);
1747   // Set Incognito to DISABLED.
1748   IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1749                                       IncognitoModePrefs::DISABLED);
1750   // Make sure Manage Extensions command is disabled.
1751   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1752   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1753   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1754   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1755   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1756
1757   // Create a popup (non-main-UI-type) browser. Settings command as well
1758   // as Extensions should be disabled.
1759   Browser* popup_browser = new Browser(
1760       Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(),
1761                             browser()->host_desktop_type()));
1762   CommandUpdater* popup_command_updater =
1763       popup_browser->command_controller()->command_updater();
1764   EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1765   EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_OPTIONS));
1766   EXPECT_TRUE(popup_command_updater->IsCommandEnabled(
1767       IDC_SHOW_BOOKMARK_MANAGER));
1768   EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1769 }
1770
1771 // Makes sure Extensions and Settings commands are disabled in certain
1772 // circumstances even though normally they should stay enabled.
1773 IN_PROC_BROWSER_TEST_F(BrowserTest,
1774                        DisableOptionsAndImportMenuItemsConsistently) {
1775   // Create a popup browser.
1776   Browser* popup_browser = new Browser(
1777       Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(),
1778                             browser()->host_desktop_type()));
1779   CommandUpdater* command_updater =
1780       popup_browser->command_controller()->command_updater();
1781   // OPTIONS and IMPORT_SETTINGS are disabled for a non-normal UI.
1782   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1783   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1784
1785   // Set Incognito to FORCED.
1786   IncognitoModePrefs::SetAvailability(popup_browser->profile()->GetPrefs(),
1787                                       IncognitoModePrefs::FORCED);
1788   // OPTIONS and IMPORT_SETTINGS are disabled when Incognito is forced.
1789   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1790   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1791   // Set Incognito to AVAILABLE.
1792   IncognitoModePrefs::SetAvailability(popup_browser->profile()->GetPrefs(),
1793                                       IncognitoModePrefs::ENABLED);
1794   // OPTIONS and IMPORT_SETTINGS are still disabled since it is a non-normal UI.
1795   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1796   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1797 }
1798
1799 namespace {
1800
1801 void OnZoomLevelChanged(const base::Closure& callback,
1802                         const HostZoomMap::ZoomLevelChange& host) {
1803   callback.Run();
1804 }
1805
1806 }  // namespace
1807
1808 #if defined(OS_WIN)
1809 // Flakes regularly on Windows XP
1810 // http://crbug.com/146040
1811 #define MAYBE_PageZoom DISABLED_PageZoom
1812 #else
1813 #define MAYBE_PageZoom PageZoom
1814 #endif
1815
1816 namespace {
1817
1818 int GetZoomPercent(const content::WebContents* contents,
1819                    bool* enable_plus,
1820                    bool* enable_minus) {
1821   int percent = ZoomController::FromWebContents(contents)->GetZoomPercent();
1822   *enable_plus = percent < contents->GetMaximumZoomPercent();
1823   *enable_minus = percent > contents->GetMinimumZoomPercent();
1824   return percent;
1825 }
1826
1827 }  // namespace
1828
1829 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_PageZoom) {
1830   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1831   bool enable_plus, enable_minus;
1832
1833   {
1834     scoped_refptr<content::MessageLoopRunner> loop_runner(
1835         new content::MessageLoopRunner);
1836     content::HostZoomMap::ZoomLevelChangedCallback callback(
1837         base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1838     scoped_ptr<content::HostZoomMap::Subscription> sub =
1839         content::HostZoomMap::GetForBrowserContext(
1840             browser()->profile())->AddZoomLevelChangedCallback(callback);
1841     chrome::Zoom(browser(), content::PAGE_ZOOM_IN);
1842     loop_runner->Run();
1843     sub.reset();
1844     EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 110);
1845     EXPECT_TRUE(enable_plus);
1846     EXPECT_TRUE(enable_minus);
1847   }
1848
1849   {
1850     scoped_refptr<content::MessageLoopRunner> loop_runner(
1851         new content::MessageLoopRunner);
1852     content::HostZoomMap::ZoomLevelChangedCallback callback(
1853         base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1854     scoped_ptr<content::HostZoomMap::Subscription> sub =
1855         content::HostZoomMap::GetForBrowserContext(
1856             browser()->profile())->AddZoomLevelChangedCallback(callback);
1857     chrome::Zoom(browser(), content::PAGE_ZOOM_RESET);
1858     loop_runner->Run();
1859     sub.reset();
1860     EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 100);
1861     EXPECT_TRUE(enable_plus);
1862     EXPECT_TRUE(enable_minus);
1863   }
1864
1865   {
1866     scoped_refptr<content::MessageLoopRunner> loop_runner(
1867         new content::MessageLoopRunner);
1868     content::HostZoomMap::ZoomLevelChangedCallback callback(
1869         base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1870     scoped_ptr<content::HostZoomMap::Subscription> sub =
1871         content::HostZoomMap::GetForBrowserContext(
1872             browser()->profile())->AddZoomLevelChangedCallback(callback);
1873     chrome::Zoom(browser(), content::PAGE_ZOOM_OUT);
1874     loop_runner->Run();
1875     sub.reset();
1876     EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 90);
1877     EXPECT_TRUE(enable_plus);
1878     EXPECT_TRUE(enable_minus);
1879   }
1880
1881   chrome::Zoom(browser(), content::PAGE_ZOOM_RESET);
1882 }
1883
1884 IN_PROC_BROWSER_TEST_F(BrowserTest, InterstitialCommandDisable) {
1885   ASSERT_TRUE(test_server()->Start());
1886   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1887   GURL url(test_server()->GetURL("empty.html"));
1888   ui_test_utils::NavigateToURL(browser(), url);
1889
1890   CommandUpdater* command_updater =
1891       browser()->command_controller()->command_updater();
1892   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1893   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_PRINT));
1894   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1895   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1896
1897   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1898
1899   TestInterstitialPage* interstitial = NULL;
1900   {
1901     scoped_refptr<content::MessageLoopRunner> loop_runner(
1902         new content::MessageLoopRunner);
1903
1904     InterstitialObserver observer(contents,
1905                                   loop_runner->QuitClosure(),
1906                                   base::Closure());
1907     interstitial = new TestInterstitialPage(contents, false, GURL());
1908     loop_runner->Run();
1909   }
1910
1911   EXPECT_TRUE(contents->ShowingInterstitialPage());
1912
1913   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1914   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_PRINT));
1915   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1916   EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1917
1918   {
1919     scoped_refptr<content::MessageLoopRunner> loop_runner(
1920         new content::MessageLoopRunner);
1921
1922     InterstitialObserver observer(contents,
1923                                   base::Closure(),
1924                                   loop_runner->QuitClosure());
1925     interstitial->Proceed();
1926     loop_runner->Run();
1927     // interstitial is deleted now.
1928   }
1929
1930   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1931   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_PRINT));
1932   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1933   EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1934 }
1935
1936 // Ensure that creating an interstitial page closes any JavaScript dialogs
1937 // that were present on the previous page.  See http://crbug.com/295695.
1938 IN_PROC_BROWSER_TEST_F(BrowserTest, InterstitialClosesDialogs) {
1939   ASSERT_TRUE(test_server()->Start());
1940   host_resolver()->AddRule("www.example.com", "127.0.0.1");
1941   GURL url(test_server()->GetURL("empty.html"));
1942   ui_test_utils::NavigateToURL(browser(), url);
1943
1944   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1945   contents->GetMainFrame()->ExecuteJavaScript(
1946       ASCIIToUTF16("alert('Dialog showing!');"));
1947   AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
1948   EXPECT_TRUE(alert->IsValid());
1949   AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
1950   EXPECT_TRUE(dialog_queue->HasActiveDialog());
1951
1952   TestInterstitialPage* interstitial = NULL;
1953   {
1954     scoped_refptr<content::MessageLoopRunner> loop_runner(
1955         new content::MessageLoopRunner);
1956
1957     InterstitialObserver observer(contents,
1958                                   loop_runner->QuitClosure(),
1959                                   base::Closure());
1960     interstitial = new TestInterstitialPage(contents, false, GURL());
1961     loop_runner->Run();
1962   }
1963
1964   // The interstitial should have closed the dialog.
1965   EXPECT_TRUE(contents->ShowingInterstitialPage());
1966   EXPECT_FALSE(dialog_queue->HasActiveDialog());
1967
1968   {
1969     scoped_refptr<content::MessageLoopRunner> loop_runner(
1970         new content::MessageLoopRunner);
1971
1972     InterstitialObserver observer(contents,
1973                                   base::Closure(),
1974                                   loop_runner->QuitClosure());
1975     interstitial->DontProceed();
1976     loop_runner->Run();
1977     // interstitial is deleted now.
1978   }
1979
1980   // Make sure input events still work in the renderer process.
1981   EXPECT_FALSE(contents->GetRenderProcessHost()->IgnoreInputEvents());
1982 }
1983
1984 #if defined(OS_MACOSX)
1985 // http://crbug.com/393218
1986 #define MAYBE_InterstitialCloseTab DISABLED_InterstitialCloseTab
1987 #else
1988 #define MAYBE_InterstitialCloseTab InterstitialCloseTab
1989 #endif
1990 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_InterstitialCloseTab) {
1991   WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1992
1993   {
1994     scoped_refptr<content::MessageLoopRunner> loop_runner(
1995         new content::MessageLoopRunner);
1996
1997     InterstitialObserver observer(contents,
1998                                   loop_runner->QuitClosure(),
1999                                   base::Closure());
2000     // Interstitial will delete itself when we close the tab.
2001     new TestInterstitialPage(contents, false, GURL());
2002     loop_runner->Run();
2003   }
2004
2005   EXPECT_TRUE(contents->ShowingInterstitialPage());
2006
2007   {
2008     scoped_refptr<content::MessageLoopRunner> loop_runner(
2009         new content::MessageLoopRunner);
2010
2011     InterstitialObserver observer(contents,
2012                                   base::Closure(),
2013                                   loop_runner->QuitClosure());
2014     chrome::CloseTab(browser());
2015     loop_runner->Run();
2016     // interstitial is deleted now.
2017   }
2018 }
2019
2020 class MockWebContentsObserver : public WebContentsObserver {
2021  public:
2022   explicit MockWebContentsObserver(WebContents* web_contents)
2023       : WebContentsObserver(web_contents),
2024         got_user_gesture_(false) {
2025   }
2026
2027   virtual void DidGetUserGesture() OVERRIDE {
2028     got_user_gesture_ = true;
2029   }
2030
2031   bool got_user_gesture() const {
2032     return got_user_gesture_;
2033   }
2034
2035   void set_got_user_gesture(bool got_it) {
2036     got_user_gesture_ = got_it;
2037   }
2038
2039  private:
2040   bool got_user_gesture_;
2041
2042   DISALLOW_COPY_AND_ASSIGN(MockWebContentsObserver);
2043 };
2044
2045 IN_PROC_BROWSER_TEST_F(BrowserTest, UserGesturesReported) {
2046   // Regression test for http://crbug.com/110707.  Also tests that a user
2047   // gesture is sent when a normal navigation (via e.g. the omnibox) is
2048   // performed.
2049   WebContents* web_contents =
2050       browser()->tab_strip_model()->GetActiveWebContents();
2051   MockWebContentsObserver mock_observer(web_contents);
2052
2053   ASSERT_TRUE(test_server()->Start());
2054   GURL url(test_server()->GetURL("empty.html"));
2055
2056   ui_test_utils::NavigateToURL(browser(), url);
2057   EXPECT_TRUE(mock_observer.got_user_gesture());
2058
2059   mock_observer.set_got_user_gesture(false);
2060   chrome::Reload(browser(), CURRENT_TAB);
2061   EXPECT_TRUE(mock_observer.got_user_gesture());
2062 }
2063
2064 // TODO(ben): this test was never enabled. It has bit-rotted since being added.
2065 // It originally lived in browser_unittest.cc, but has been moved here to make
2066 // room for real browser unit tests.
2067 #if 0
2068 class BrowserTest2 : public InProcessBrowserTest {
2069  public:
2070   BrowserTest2() {
2071     host_resolver_proc_ = new net::RuleBasedHostResolverProc(NULL);
2072     // Avoid making external DNS lookups. In this test we don't need this
2073     // to succeed.
2074     host_resolver_proc_->AddSimulatedFailure("*.google.com");
2075     scoped_host_resolver_proc_.Init(host_resolver_proc_.get());
2076   }
2077
2078  private:
2079   scoped_refptr<net::RuleBasedHostResolverProc> host_resolver_proc_;
2080   net::ScopedDefaultHostResolverProc scoped_host_resolver_proc_;
2081 };
2082
2083 IN_PROC_BROWSER_TEST_F(BrowserTest2, NoTabsInPopups) {
2084   chrome::RegisterAppPrefs(L"Test");
2085
2086   // We start with a normal browser with one tab.
2087   EXPECT_EQ(1, browser()->tab_strip_model()->count());
2088
2089   // Open a popup browser with a single blank foreground tab.
2090   Browser* popup_browser = new Browser(
2091       Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile()));
2092   chrome::AddTabAt(popup_browser, GURL(), -1, true);
2093   EXPECT_EQ(1, popup_browser->tab_strip_model()->count());
2094
2095   // Now try opening another tab in the popup browser.
2096   AddTabWithURLParams params1(url, content::PAGE_TRANSITION_TYPED);
2097   popup_browser->AddTabWithURL(&params1);
2098   EXPECT_EQ(popup_browser, params1.target);
2099
2100   // The popup should still only have one tab.
2101   EXPECT_EQ(1, popup_browser->tab_strip_model()->count());
2102
2103   // The normal browser should now have two.
2104   EXPECT_EQ(2, browser()->tab_strip_model()->count());
2105
2106   // Open an app frame browser with a single blank foreground tab.
2107   Browser* app_browser = new Browser(Browser::CreateParams::CreateForApp(
2108       L"Test", browser()->profile(), false));
2109   chrome::AddTabAt(app_browser, GURL(), -1, true);
2110   EXPECT_EQ(1, app_browser->tab_strip_model()->count());
2111
2112   // Now try opening another tab in the app browser.
2113   AddTabWithURLParams params2(GURL(url::kAboutBlankURL),
2114                               content::PAGE_TRANSITION_TYPED);
2115   app_browser->AddTabWithURL(&params2);
2116   EXPECT_EQ(app_browser, params2.target);
2117
2118   // The popup should still only have one tab.
2119   EXPECT_EQ(1, app_browser->tab_strip_model()->count());
2120
2121   // The normal browser should now have three.
2122   EXPECT_EQ(3, browser()->tab_strip_model()->count());
2123
2124   // Open an app frame popup browser with a single blank foreground tab.
2125   Browser* app_popup_browser = new Browser(Browser::CreateParams::CreateForApp(
2126       L"Test", browser()->profile(), false));
2127   chrome::AddTabAt(app_popup_browser, GURL(), -1, true);
2128   EXPECT_EQ(1, app_popup_browser->tab_strip_model()->count());
2129
2130   // Now try opening another tab in the app popup browser.
2131   AddTabWithURLParams params3(GURL(url::kAboutBlankURL),
2132                               content::PAGE_TRANSITION_TYPED);
2133   app_popup_browser->AddTabWithURL(&params3);
2134   EXPECT_EQ(app_popup_browser, params3.target);
2135
2136   // The popup should still only have one tab.
2137   EXPECT_EQ(1, app_popup_browser->tab_strip_model()->count());
2138
2139   // The normal browser should now have four.
2140   EXPECT_EQ(4, browser()->tab_strip_model()->count());
2141
2142   // Close the additional browsers.
2143   popup_browser->tab_strip_model()->CloseAllTabs();
2144   app_browser->tab_strip_model()->CloseAllTabs();
2145   app_popup_browser->tab_strip_model()->CloseAllTabs();
2146 }
2147 #endif
2148
2149 IN_PROC_BROWSER_TEST_F(BrowserTest, WindowOpenClose) {
2150   CommandLine::ForCurrentProcess()->AppendSwitch(
2151       switches::kDisablePopupBlocking);
2152   GURL url = ui_test_utils::GetTestUrl(
2153       base::FilePath(), base::FilePath().AppendASCII("window.close.html"));
2154
2155   base::string16 title = ASCIIToUTF16("Title Of Awesomeness");
2156   content::TitleWatcher title_watcher(
2157       browser()->tab_strip_model()->GetActiveWebContents(), title);
2158   ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 2);
2159   EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
2160 }
2161
2162 // TODO(linux_aura) http://crbug.com/163931
2163 // Mac disabled: http://crbug.com/169820
2164 #if !defined(OS_MACOSX) && \
2165     !(defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA))
2166 IN_PROC_BROWSER_TEST_F(BrowserTest, FullscreenBookmarkBar) {
2167 #if defined(OS_WIN) && defined(USE_ASH)
2168   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2169   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2170     return;
2171 #endif
2172
2173   chrome::ToggleBookmarkBar(browser());
2174   EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2175   chrome::ToggleFullscreenMode(browser());
2176   EXPECT_TRUE(browser()->window()->IsFullscreen());
2177 #if defined(OS_MACOSX)
2178   EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2179 #elif defined(OS_CHROMEOS)
2180   // TODO(jamescook): If immersive fullscreen is disabled by default, test
2181   // for BookmarkBar::HIDDEN.
2182   EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2183 #else
2184   EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2185 #endif
2186 }
2187 #endif
2188
2189 IN_PROC_BROWSER_TEST_F(BrowserTest, DisallowFileUrlUniversalAccessTest) {
2190   GURL url = ui_test_utils::GetTestUrl(
2191       base::FilePath(),
2192       base::FilePath().AppendASCII("fileurl_universalaccess.html"));
2193
2194   base::string16 expected_title(ASCIIToUTF16("Disallowed"));
2195   content::TitleWatcher title_watcher(
2196       browser()->tab_strip_model()->GetActiveWebContents(), expected_title);
2197   title_watcher.AlsoWaitForTitle(ASCIIToUTF16("Allowed"));
2198   ui_test_utils::NavigateToURL(browser(), url);
2199   ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());
2200 }
2201
2202 class KioskModeTest : public BrowserTest {
2203  public:
2204   KioskModeTest() {}
2205
2206   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2207     command_line->AppendSwitch(switches::kKioskMode);
2208   }
2209 };
2210
2211 #if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
2212 // Mac: http://crbug.com/103912
2213 // Linux: http://crbug.com/163931
2214 #define MAYBE_EnableKioskModeTest DISABLED_EnableKioskModeTest
2215 #else
2216 #define MAYBE_EnableKioskModeTest EnableKioskModeTest
2217 #endif
2218 IN_PROC_BROWSER_TEST_F(KioskModeTest, MAYBE_EnableKioskModeTest) {
2219   // Check if browser is in fullscreen mode.
2220   ASSERT_TRUE(browser()->window()->IsFullscreen());
2221   ASSERT_FALSE(browser()->window()->IsFullscreenBubbleVisible());
2222 }
2223
2224 #if defined(OS_WIN)
2225 // This test verifies that Chrome can be launched with a user-data-dir path
2226 // which contains non ASCII characters.
2227 class LaunchBrowserWithNonAsciiUserDatadir : public BrowserTest {
2228  public:
2229   LaunchBrowserWithNonAsciiUserDatadir() {}
2230
2231   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2232     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
2233     base::FilePath tmp_profile = temp_dir_.path().AppendASCII("tmp_profile");
2234     tmp_profile = tmp_profile.Append(L"Test Chrome G\u00E9raldine");
2235
2236     ASSERT_TRUE(base::CreateDirectory(tmp_profile));
2237     command_line->AppendSwitchPath(switches::kUserDataDir, tmp_profile);
2238   }
2239
2240   base::ScopedTempDir temp_dir_;
2241 };
2242
2243 IN_PROC_BROWSER_TEST_F(LaunchBrowserWithNonAsciiUserDatadir,
2244                        TestNonAsciiUserDataDir) {
2245   // Verify that the window is present.
2246   ASSERT_TRUE(browser());
2247 }
2248 #endif  // defined(OS_WIN)
2249
2250 // Tests to ensure that the browser continues running in the background after
2251 // the last window closes.
2252 class RunInBackgroundTest : public BrowserTest {
2253  public:
2254   RunInBackgroundTest() {}
2255
2256   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2257     command_line->AppendSwitch(switches::kKeepAliveForTest);
2258   }
2259 };
2260
2261 IN_PROC_BROWSER_TEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) {
2262   // Close the browser window, then open a new one - the browser should keep
2263   // running.
2264   Profile* profile = browser()->profile();
2265   EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2266   content::WindowedNotificationObserver observer(
2267       chrome::NOTIFICATION_BROWSER_CLOSED,
2268       content::Source<Browser>(browser()));
2269   chrome::CloseWindow(browser());
2270   observer.Wait();
2271   EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
2272
2273   ui_test_utils::BrowserAddedObserver browser_added_observer;
2274   chrome::NewEmptyWindow(profile, chrome::GetActiveDesktop());
2275   browser_added_observer.WaitForSingleNewBrowser();
2276
2277   EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2278 }
2279
2280 // Tests to ensure that the browser continues running in the background after
2281 // the last window closes.
2282 class NoStartupWindowTest : public BrowserTest {
2283  public:
2284   NoStartupWindowTest() {}
2285
2286   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2287     command_line->AppendSwitch(switches::kNoStartupWindow);
2288     command_line->AppendSwitch(switches::kKeepAliveForTest);
2289   }
2290 };
2291
2292 IN_PROC_BROWSER_TEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) {
2293 #if defined(OS_WIN) && defined(USE_ASH)
2294   // kNoStartupWindow doesn't make sense in Metro+Ash.
2295   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2296     return;
2297 #endif
2298
2299   // No browser window should be started by default.
2300   EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
2301
2302   // Starting a browser window should work just fine.
2303   ui_test_utils::BrowserAddedObserver browser_added_observer;
2304   CreateBrowser(ProfileManager::GetActiveUserProfile());
2305   browser_added_observer.WaitForSingleNewBrowser();
2306
2307   EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2308 }
2309
2310 // Chromeos needs to track app windows because it considers them to be part of
2311 // session state.
2312 #if !defined(OS_CHROMEOS)
2313 IN_PROC_BROWSER_TEST_F(NoStartupWindowTest, DontInitSessionServiceForApps) {
2314 #if defined(OS_WIN) && defined(USE_ASH)
2315   // kNoStartupWindow doesn't make sense in Metro+Ash.
2316   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2317     return;
2318 #endif
2319
2320   Profile* profile = ProfileManager::GetActiveUserProfile();
2321
2322   SessionService* session_service =
2323       SessionServiceFactory::GetForProfile(profile);
2324   ASSERT_FALSE(session_service->processed_any_commands());
2325
2326   ui_test_utils::BrowserAddedObserver browser_added_observer;
2327   CreateBrowserForApp("blah", profile);
2328   browser_added_observer.WaitForSingleNewBrowser();
2329
2330   ASSERT_FALSE(session_service->processed_any_commands());
2331 }
2332 #endif  // !defined(OS_CHROMEOS)
2333
2334 // This test needs to be placed outside the anonymous namespace because we
2335 // need to access private type of Browser.
2336 class AppModeTest : public BrowserTest {
2337  public:
2338   AppModeTest() {}
2339
2340   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2341     GURL url = ui_test_utils::GetTestUrl(
2342        base::FilePath(), base::FilePath().AppendASCII("title1.html"));
2343     command_line->AppendSwitchASCII(switches::kApp, url.spec());
2344   }
2345 };
2346
2347 IN_PROC_BROWSER_TEST_F(AppModeTest, EnableAppModeTest) {
2348 #if defined(OS_WIN) && defined(USE_ASH)
2349   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2350   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2351     return;
2352 #endif
2353
2354   // Test that an application browser window loads correctly.
2355
2356   // Verify the browser is in application mode.
2357   EXPECT_TRUE(browser()->is_app());
2358 }
2359
2360 // Confirm chrome://version contains some expected content.
2361 IN_PROC_BROWSER_TEST_F(BrowserTest, AboutVersion) {
2362   ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIVersionURL));
2363   WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2364   ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("WebKit"), true, true,
2365                                       NULL, NULL),
2366             0);
2367   ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("OS"), true, true,
2368                                       NULL, NULL),
2369             0);
2370   ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("JavaScript"), true,
2371                                       true, NULL, NULL),
2372             0);
2373 }
2374
2375 static const base::FilePath::CharType* kTestDir =
2376     FILE_PATH_LITERAL("click_modifier");
2377 static const char kFirstPageTitle[] = "First window";
2378 static const char kSecondPageTitle[] = "New window!";
2379
2380 class ClickModifierTest : public InProcessBrowserTest {
2381  public:
2382   ClickModifierTest() {
2383   }
2384
2385   // Returns a url that opens a new window or tab when clicked, via javascript.
2386   GURL GetWindowOpenURL() {
2387     return ui_test_utils::GetTestUrl(
2388       base::FilePath(kTestDir),
2389       base::FilePath(FILE_PATH_LITERAL("window_open.html")));
2390   }
2391
2392   // Returns a url that follows a simple link when clicked, unless affected by
2393   // modifiers.
2394   GURL GetHrefURL() {
2395     return ui_test_utils::GetTestUrl(
2396       base::FilePath(kTestDir),
2397       base::FilePath(FILE_PATH_LITERAL("href.html")));
2398   }
2399
2400   base::string16 getFirstPageTitle() {
2401     return ASCIIToUTF16(kFirstPageTitle);
2402   }
2403
2404   base::string16 getSecondPageTitle() {
2405     return ASCIIToUTF16(kSecondPageTitle);
2406   }
2407
2408   // Loads our test page and simulates a single click using the supplied button
2409   // and modifiers.  The click will cause either a navigation or the creation of
2410   // a new window or foreground or background tab.  We verify that the expected
2411   // disposition occurs.
2412   void RunTest(Browser* browser,
2413                const GURL& url,
2414                int modifiers,
2415                blink::WebMouseEvent::Button button,
2416                WindowOpenDisposition disposition) {
2417     ui_test_utils::NavigateToURL(browser, url);
2418     EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2419                                           browser->host_desktop_type()));
2420     EXPECT_EQ(1, browser->tab_strip_model()->count());
2421     content::WebContents* web_contents =
2422         browser->tab_strip_model()->GetActiveWebContents();
2423     EXPECT_EQ(url, web_contents->GetURL());
2424
2425     if (disposition == CURRENT_TAB) {
2426       content::WebContents* web_contents =
2427           browser->tab_strip_model()->GetActiveWebContents();
2428       content::TestNavigationObserver same_tab_observer(web_contents);
2429       SimulateMouseClick(web_contents, modifiers, button);
2430       same_tab_observer.Wait();
2431       EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2432                                             browser->host_desktop_type()));
2433       EXPECT_EQ(1, browser->tab_strip_model()->count());
2434       EXPECT_EQ(getSecondPageTitle(), web_contents->GetTitle());
2435       return;
2436     }
2437
2438     content::WindowedNotificationObserver observer(
2439         chrome::NOTIFICATION_TAB_ADDED,
2440         content::NotificationService::AllSources());
2441     SimulateMouseClick(web_contents, modifiers, button);
2442     observer.Wait();
2443
2444     if (disposition == NEW_WINDOW) {
2445       EXPECT_EQ(2u, chrome::GetBrowserCount(browser->profile(),
2446                                             browser->host_desktop_type()));
2447       return;
2448     }
2449
2450     EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2451                                           browser->host_desktop_type()));
2452     EXPECT_EQ(2, browser->tab_strip_model()->count());
2453     web_contents = browser->tab_strip_model()->GetActiveWebContents();
2454     WaitForLoadStop(web_contents);
2455     if (disposition == NEW_FOREGROUND_TAB) {
2456       EXPECT_EQ(getSecondPageTitle(), web_contents->GetTitle());
2457     } else {
2458       ASSERT_EQ(NEW_BACKGROUND_TAB, disposition);
2459       EXPECT_EQ(getFirstPageTitle(), web_contents->GetTitle());
2460     }
2461   }
2462
2463  private:
2464   DISALLOW_COPY_AND_ASSIGN(ClickModifierTest);
2465 };
2466
2467 // Tests for clicking on elements with handlers that run window.open.
2468
2469 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenBasicClickTest) {
2470   int modifiers = 0;
2471   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2472   WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2473   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2474 }
2475
2476 // TODO(ericu): Alt-click behavior on window.open is platform-dependent and not
2477 // well defined.  Should we add tests so we know if it changes?
2478
2479 // Shift-clicks open in a new window.
2480 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenShiftClickTest) {
2481   int modifiers = blink::WebInputEvent::ShiftKey;
2482   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2483   WindowOpenDisposition disposition = NEW_WINDOW;
2484   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2485 }
2486
2487 // Control-clicks open in a background tab.
2488 // On OSX meta [the command key] takes the place of control.
2489 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenControlClickTest) {
2490 #if defined(OS_MACOSX)
2491   int modifiers = blink::WebInputEvent::MetaKey;
2492 #else
2493   int modifiers = blink::WebInputEvent::ControlKey;
2494 #endif
2495   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2496   WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2497   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2498 }
2499
2500 // Control-shift-clicks open in a foreground tab.
2501 // On OSX meta [the command key] takes the place of control.
2502 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenControlShiftClickTest) {
2503 #if defined(OS_MACOSX)
2504   int modifiers = blink::WebInputEvent::MetaKey;
2505 #else
2506   int modifiers = blink::WebInputEvent::ControlKey;
2507 #endif
2508   modifiers |= blink::WebInputEvent::ShiftKey;
2509   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2510   WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2511   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2512 }
2513
2514 // Middle-clicks open in a background tab.
2515 #if defined(OS_LINUX)
2516 // http://crbug.com/396347
2517 #define MAYBE_WindowOpenMiddleClickTest DISABLED_WindowOpenMiddleClickTest
2518 #else
2519 #define MAYBE_WindowOpenMiddleClickTest WindowOpenMiddleClickTest
2520 #endif
2521 IN_PROC_BROWSER_TEST_F(ClickModifierTest, MAYBE_WindowOpenMiddleClickTest) {
2522   int modifiers = 0;
2523   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2524   WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2525   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2526 }
2527
2528 // Shift-middle-clicks open in a foreground tab.
2529 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenShiftMiddleClickTest) {
2530   int modifiers = blink::WebInputEvent::ShiftKey;
2531   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2532   WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2533   RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2534 }
2535
2536 // Tests for clicking on normal links.
2537
2538 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefBasicClickTest) {
2539   int modifiers = 0;
2540   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2541   WindowOpenDisposition disposition = CURRENT_TAB;
2542   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2543 }
2544
2545 // TODO(ericu): Alt-click behavior on links is platform-dependent and not well
2546 // defined.  Should we add tests so we know if it changes?
2547
2548 // Shift-clicks open in a new window.
2549 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefShiftClickTest) {
2550   int modifiers = blink::WebInputEvent::ShiftKey;
2551   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2552   WindowOpenDisposition disposition = NEW_WINDOW;
2553   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2554 }
2555
2556 // Control-clicks open in a background tab.
2557 // On OSX meta [the command key] takes the place of control.
2558 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefControlClickTest) {
2559 #if defined(OS_MACOSX)
2560   int modifiers = blink::WebInputEvent::MetaKey;
2561 #else
2562   int modifiers = blink::WebInputEvent::ControlKey;
2563 #endif
2564   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2565   WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2566   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2567 }
2568
2569 // Control-shift-clicks open in a foreground tab.
2570 // On OSX meta [the command key] takes the place of control.
2571 // http://crbug.com/396347
2572 IN_PROC_BROWSER_TEST_F(ClickModifierTest, DISABLED_HrefControlShiftClickTest) {
2573 #if defined(OS_MACOSX)
2574   int modifiers = blink::WebInputEvent::MetaKey;
2575 #else
2576   int modifiers = blink::WebInputEvent::ControlKey;
2577 #endif
2578   modifiers |= blink::WebInputEvent::ShiftKey;
2579   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2580   WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2581   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2582 }
2583
2584 // Middle-clicks open in a background tab.
2585 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefMiddleClickTest) {
2586   int modifiers = 0;
2587   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2588   WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2589   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2590 }
2591
2592 // Shift-middle-clicks open in a foreground tab.
2593 // http://crbug.com/396347
2594 IN_PROC_BROWSER_TEST_F(ClickModifierTest, DISABLED_HrefShiftMiddleClickTest) {
2595   int modifiers = blink::WebInputEvent::ShiftKey;
2596   blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2597   WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2598   RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2599 }
2600
2601 IN_PROC_BROWSER_TEST_F(BrowserTest, GetSizeForNewRenderView) {
2602   // The instant extended NTP has javascript that does not work with
2603   // ui_test_utils::NavigateToURL.  The NTP rvh reloads when the browser tries
2604   // to navigate away from the page, which causes the WebContents to end up in
2605   // an inconsistent state. (is_loaded = true, last_commited_url=ntp,
2606   // visible_url=title1.html)
2607   browser()->profile()->GetPrefs()->SetBoolean(prefs::kWebKitJavascriptEnabled,
2608                                                false);
2609   ASSERT_TRUE(test_server()->Start());
2610   // Create an HTTPS server for cross-site transition.
2611   net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
2612                                            net::SpawnedTestServer::kLocalhost,
2613                                            base::FilePath(kDocRoot));
2614   ASSERT_TRUE(https_test_server.Start());
2615
2616   // Start with NTP.
2617   ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab"));
2618   ASSERT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
2619   WebContents* web_contents =
2620       browser()->tab_strip_model()->GetActiveWebContents();
2621   content::RenderViewHost* prev_rvh = web_contents->GetRenderViewHost();
2622   const int height_inset =
2623       browser()->window()->GetRenderViewHeightInsetWithDetachedBookmarkBar();
2624   const gfx::Size initial_wcv_size =
2625       web_contents->GetContainerBounds().size();
2626   RenderViewSizeObserver observer(web_contents, browser()->window());
2627
2628   // Navigate to a non-NTP page, without resizing WebContentsView.
2629   ui_test_utils::NavigateToURL(browser(),
2630                                test_server()->GetURL("files/title1.html"));
2631   ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2632   // A new RenderViewHost should be created.
2633   EXPECT_NE(prev_rvh, web_contents->GetRenderViewHost());
2634   prev_rvh = web_contents->GetRenderViewHost();
2635   gfx::Size rwhv_create_size0, rwhv_commit_size0, wcv_commit_size0;
2636   observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2637                                     &rwhv_create_size0,
2638                                     &rwhv_commit_size0,
2639                                     &wcv_commit_size0);
2640   // The create height of RenderWidgetHostView should include the height inset.
2641   EXPECT_EQ(gfx::Size(initial_wcv_size.width(),
2642                       initial_wcv_size.height() + height_inset),
2643             rwhv_create_size0);
2644   // When a navigation entry is committed, the size of RenderWidgetHostView
2645   // should be the same as when it was first created.
2646   EXPECT_EQ(rwhv_create_size0, rwhv_commit_size0);
2647   // Sizes of the current RenderWidgetHostView and WebContentsView should not
2648   // change before and after WebContentsDelegate::DidNavigateMainFramePostCommit
2649   // (implemented by Browser); we obtain the sizes before PostCommit via
2650   // WebContentsObserver::NavigationEntryCommitted (implemented by
2651   // RenderViewSizeObserver).
2652   EXPECT_EQ(rwhv_commit_size0,
2653             web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2654 // The behavior differs between OSX and views.
2655 // In OSX, the wcv does not change size until after the commit, when the
2656 // bookmark bar disappears (correct).
2657 // In views, the wcv changes size at commit time.
2658 #if defined(OS_MACOSX)
2659   EXPECT_EQ(gfx::Size(wcv_commit_size0.width(),
2660                       wcv_commit_size0.height() + height_inset),
2661             web_contents->GetContainerBounds().size());
2662 #else
2663   EXPECT_EQ(wcv_commit_size0, web_contents->GetContainerBounds().size());
2664 #endif
2665
2666   // Navigate to another non-NTP page, without resizing WebContentsView.
2667   ui_test_utils::NavigateToURL(browser(),
2668                                https_test_server.GetURL("files/title2.html"));
2669   ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2670   // A new RenderVieHost should be created.
2671   EXPECT_NE(prev_rvh, web_contents->GetRenderViewHost());
2672   gfx::Size rwhv_create_size1, rwhv_commit_size1, wcv_commit_size1;
2673   observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2674                                     &rwhv_create_size1,
2675                                     &rwhv_commit_size1,
2676                                     &wcv_commit_size1);
2677   EXPECT_EQ(rwhv_create_size1, rwhv_commit_size1);
2678   EXPECT_EQ(rwhv_commit_size1,
2679             web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2680   EXPECT_EQ(wcv_commit_size1, web_contents->GetContainerBounds().size());
2681
2682   // Navigate from NTP to a non-NTP page, resizing WebContentsView while
2683   // navigation entry is pending.
2684   ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab"));
2685   gfx::Size wcv_resize_insets(1, 1);
2686   observer.set_wcv_resize_insets(wcv_resize_insets);
2687   ui_test_utils::NavigateToURL(browser(),
2688                                test_server()->GetURL("files/title2.html"));
2689   ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2690   gfx::Size rwhv_create_size2, rwhv_commit_size2, wcv_commit_size2;
2691   observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2692                                     &rwhv_create_size2,
2693                                     &rwhv_commit_size2,
2694                                     &wcv_commit_size2);
2695
2696   // The behavior on OSX and Views is incorrect in this edge case, but they are
2697   // differently incorrect.
2698   // The behavior should be:
2699   // initial wcv size: (100,100)  (to choose random numbers)
2700   // initial rwhv size: (100,140)
2701   // commit wcv size: (101, 101)
2702   // commit rwhv size: (101, 141)
2703   // final wcv size: (101, 141)
2704   // final rwhv size: (101, 141)
2705   //
2706   // On OSX, the commit rwhv size is (101, 101)
2707   // On views, the commit wcv size is (101, 141)
2708   // All other sizes are correct.
2709
2710   // The create height of RenderWidgetHostView should include the height inset.
2711   EXPECT_EQ(gfx::Size(initial_wcv_size.width(),
2712                       initial_wcv_size.height() + height_inset),
2713             rwhv_create_size2);
2714   gfx::Size exp_commit_size(initial_wcv_size);
2715
2716 #if defined(OS_MACOSX)
2717   exp_commit_size.Enlarge(wcv_resize_insets.width(),
2718                           wcv_resize_insets.height());
2719 #else
2720   exp_commit_size.Enlarge(wcv_resize_insets.width(),
2721                           wcv_resize_insets.height() + height_inset);
2722 #endif
2723   EXPECT_EQ(exp_commit_size, rwhv_commit_size2);
2724   EXPECT_EQ(exp_commit_size, wcv_commit_size2);
2725   gfx::Size exp_final_size(initial_wcv_size);
2726   exp_final_size.Enlarge(wcv_resize_insets.width(),
2727                          wcv_resize_insets.height() + height_inset);
2728   EXPECT_EQ(exp_final_size,
2729             web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2730   EXPECT_EQ(exp_final_size, web_contents->GetContainerBounds().size());
2731 }