1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/file_util.h"
6 #include "base/files/file.h"
7 #include "base/files/file_enumerator.h"
9 #include "base/path_service.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/ui/browser.h"
15 #include "chrome/browser/ui/browser_window.h"
16 #include "chrome/browser/ui/tabs/tab_strip_model.h"
17 #include "chrome/common/chrome_paths.h"
18 #include "chrome/test/base/in_process_browser_test.h"
19 #include "chrome/test/base/ui_test_utils.h"
20 #include "content/public/browser/navigation_controller.h"
21 #include "content/public/browser/notification_observer.h"
22 #include "content/public/browser/render_view_host.h"
23 #include "content/public/browser/web_contents.h"
24 #include "content/public/test/browser_test_utils.h"
25 #include "net/test/embedded_test_server/embedded_test_server.h"
26 #include "third_party/skia/include/core/SkBitmap.h"
27 #include "ui/base/clipboard/clipboard.h"
28 #include "ui/gfx/codec/png_codec.h"
29 #include "ui/gfx/screen.h"
31 using content::NavigationController
;
32 using content::WebContents
;
34 // Note: All tests in here require the internal PDF plugin, so they're disabled
35 // in non-official builds. We still compile them though, to prevent bitrot.
39 // Include things like browser frame and scrollbar and make sure we're bigger
40 // than the test pdf document.
41 static const int kBrowserWidth
= 1000;
42 static const int kBrowserHeight
= 600;
44 class PDFBrowserTest
: public InProcessBrowserTest
,
45 public testing::WithParamInterface
<int>,
46 public content::NotificationObserver
{
49 : snapshot_different_(true),
50 next_dummy_search_value_(0),
51 load_stop_notification_count_(0) {
52 base::FilePath src_dir
;
53 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT
, &src_dir
));
54 pdf_test_server_
.ServeFilesFromDirectory(src_dir
.AppendASCII(
55 "chrome/test/data/pdf_private"));
59 // Use our own TestServer so that we can serve files from the pdf directory.
60 net::test_server::EmbeddedTestServer
* pdf_test_server() {
61 return &pdf_test_server_
;
64 int load_stop_notification_count() const {
65 return load_stop_notification_count_
;
69 // Make sure to set the window size before rendering, as otherwise rendering
70 // to a smaller window and then expanding leads to slight anti-aliasing
71 // differences of the text and the pixel comparison fails.
72 gfx::Rect
bounds(gfx::Rect(0, 0, kBrowserWidth
, kBrowserHeight
));
73 gfx::Rect screen_bounds
=
74 gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().bounds();
75 ASSERT_GT(screen_bounds
.width(), kBrowserWidth
);
76 ASSERT_GT(screen_bounds
.height(), kBrowserHeight
);
77 browser()->window()->SetBounds(bounds
);
79 GURL
url(ui_test_utils::GetTestUrl(
80 base::FilePath(FILE_PATH_LITERAL("pdf_private")),
81 base::FilePath(FILE_PATH_LITERAL("pdf_browsertest.pdf"))));
82 ui_test_utils::NavigateToURL(browser(), url
);
85 bool VerifySnapshot(const std::string
& expected_filename
) {
86 snapshot_different_
= true;
87 expected_filename_
= expected_filename
;
88 WebContents
* web_contents
=
89 browser()->tab_strip_model()->GetActiveWebContents();
92 content::RenderWidgetHost
* rwh
= web_contents
->GetRenderViewHost();
93 rwh
->CopyFromBackingStore(
96 base::Bind(&PDFBrowserTest::CopyFromBackingStoreCallback
, this),
97 SkBitmap::kARGB_8888_Config
);
99 content::RunMessageLoop();
101 if (snapshot_different_
) {
102 LOG(INFO
) << "Rendering didn't match, see result " <<
103 snapshot_filename_
.value().c_str();
105 return !snapshot_different_
;
108 void WaitForResponse() {
109 // Even if the plugin has loaded the data or scrolled, because of how
110 // pepper painting works, we might not have the data. One way to force this
111 // to be flushed is to do a find operation, since on this two-page test
112 // document, it'll wait for us to flush the renderer message loop twice and
113 // also the browser's once, at which point we're guaranteed to have updated
114 // the backingstore. Hacky, but it works.
115 // Note that we need to change the text each time, because if we don't the
116 // renderer code will think the second message is to go to next result, but
117 // there are none so the plugin will assert.
119 base::string16 query
= base::UTF8ToUTF16(
120 std::string("xyzxyz" + base::IntToString(next_dummy_search_value_
++)));
121 ASSERT_EQ(0, ui_test_utils::FindInPage(
122 browser()->tab_strip_model()->GetActiveWebContents(),
123 query
, true, false, NULL
, NULL
));
127 void CopyFromBackingStoreCallback(bool success
, const SkBitmap
& bitmap
) {
128 base::MessageLoopForUI::current()->Quit();
129 ASSERT_EQ(success
, true);
130 base::FilePath reference
= ui_test_utils::GetTestFilePath(
131 base::FilePath(FILE_PATH_LITERAL("pdf_private")),
132 base::FilePath().AppendASCII(expected_filename_
));
133 base::File::Info info
;
134 ASSERT_TRUE(base::GetFileInfo(reference
, &info
));
135 int size
= static_cast<size_t>(info
.size
);
136 scoped_ptr
<char[]> data(new char[size
]);
137 ASSERT_EQ(size
, base::ReadFile(reference
, data
.get(), size
));
140 std::vector
<unsigned char> decoded
;
141 ASSERT_TRUE(gfx::PNGCodec::Decode(
142 reinterpret_cast<unsigned char*>(data
.get()), size
,
143 gfx::PNGCodec::FORMAT_BGRA
, &decoded
, &w
, &h
));
144 int32
* ref_pixels
= reinterpret_cast<int32
*>(&decoded
[0]);
146 int32
* pixels
= static_cast<int32
*>(bitmap
.getPixels());
148 // Get the background color, and use it to figure out the x-offsets in
149 // each image. The reason is that depending on the theme in the OS, the
150 // same browser width can lead to slightly different plugin sizes, so the
151 // pdf content will start at different x offsets.
152 // Also note that the images we saved are cut off before the scrollbar, as
153 // that'll change depending on the theme, and also cut off vertically so
154 // that the ui controls don't show up, as those fade-in and so the timing
155 // will affect their transparency.
156 int32 bg_color
= ref_pixels
[0];
157 int ref_x_offset
, snapshot_x_offset
;
158 for (ref_x_offset
= 0; ref_x_offset
< w
; ++ref_x_offset
) {
159 if (ref_pixels
[ref_x_offset
] != bg_color
)
163 for (snapshot_x_offset
= 0; snapshot_x_offset
< bitmap
.width();
164 ++snapshot_x_offset
) {
165 if (pixels
[snapshot_x_offset
] != bg_color
)
169 int x_max
= std::min(
170 w
- ref_x_offset
, bitmap
.width() - snapshot_x_offset
);
171 int y_max
= std::min(h
, bitmap
.height());
172 int stride
= bitmap
.rowBytes();
173 snapshot_different_
= false;
174 for (int y
= 0; y
< y_max
&& !snapshot_different_
; ++y
) {
175 for (int x
= 0; x
< x_max
&& !snapshot_different_
; ++x
) {
176 if (pixels
[y
* stride
/ sizeof(int32
) + x
+ snapshot_x_offset
] !=
177 ref_pixels
[y
* w
+ x
+ ref_x_offset
])
178 snapshot_different_
= true;
182 if (snapshot_different_
) {
183 std::vector
<unsigned char> png_data
;
184 gfx::PNGCodec::EncodeBGRASkBitmap(bitmap
, false, &png_data
);
185 if (base::CreateTemporaryFile(&snapshot_filename_
)) {
186 base::WriteFile(snapshot_filename_
,
187 reinterpret_cast<char*>(&png_data
[0]), png_data
.size());
192 // content::NotificationObserver
193 virtual void Observe(int type
,
194 const content::NotificationSource
& source
,
195 const content::NotificationDetails
& details
) {
196 if (type
== content::NOTIFICATION_LOAD_STOP
) {
197 load_stop_notification_count_
++;
201 // True if the snapshot differed from the expected value.
202 bool snapshot_different_
;
203 // Internal variable used to synchronize to the renderer.
204 int next_dummy_search_value_
;
205 // The filename of the bitmap to compare the snapshot to.
206 std::string expected_filename_
;
207 // If the snapshot is different, holds the location where it's saved.
208 base::FilePath snapshot_filename_
;
209 // How many times we've seen chrome::LOAD_STOP.
210 int load_stop_notification_count_
;
212 net::test_server::EmbeddedTestServer pdf_test_server_
;
216 // TODO(thestig): http://crbug.com/79837
217 // Tests basic PDF rendering. This can be broken depending on bad merges with
218 // the vendor, so it's important that we have basic sanity checking.
219 IN_PROC_BROWSER_TEST_F(PDFBrowserTest
, DISABLED_Basic
) {
220 ASSERT_NO_FATAL_FAILURE(Load());
221 ASSERT_NO_FATAL_FAILURE(WaitForResponse());
222 // OS X uses CoreText, and FreeType renders slightly different on Linux and
224 #if defined(OS_MACOSX)
225 // The bots render differently than locally, see http://crbug.com/142531.
226 ASSERT_TRUE(VerifySnapshot("pdf_browsertest_mac.png") ||
227 VerifySnapshot("pdf_browsertest_mac2.png"));
228 #elif defined(OS_LINUX)
229 ASSERT_TRUE(VerifySnapshot("pdf_browsertest_linux.png"));
231 ASSERT_TRUE(VerifySnapshot("pdf_browsertest.png"));
235 #if (!defined(GOOGLE_CHROME_BUILD) || defined(OS_CHROMEOS)) || \
236 (defined(OS_LINUX) || defined(OS_MACOSX))
237 // TODO(sanjeevr): http://crbug.com/79837, http://crbug.com/332778
238 #define MAYBE_Scroll DISABLED_Scroll
240 #define MAYBE_Scroll Scroll
242 // Tests that scrolling works.
243 IN_PROC_BROWSER_TEST_F(PDFBrowserTest
, MAYBE_Scroll
) {
244 ASSERT_NO_FATAL_FAILURE(Load());
246 // We use wheel mouse event since that's the only one we can easily push to
247 // the renderer. There's no way to push a cross-platform keyboard event at
249 blink::WebMouseWheelEvent wheel_event
;
250 wheel_event
.type
= blink::WebInputEvent::MouseWheel
;
251 wheel_event
.deltaY
= -200;
252 wheel_event
.wheelTicksY
= -2;
253 WebContents
* web_contents
=
254 browser()->tab_strip_model()->GetActiveWebContents();
255 web_contents
->GetRenderViewHost()->ForwardWheelEvent(wheel_event
);
256 ASSERT_NO_FATAL_FAILURE(WaitForResponse());
259 ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
260 browser()->tab_strip_model()->GetActiveWebContents(),
261 "window.domAutomationController.send(plugin.pageYOffset())",
263 ASSERT_GT(y_offset
, 0);
266 #if (!defined(GOOGLE_CHROME_BUILD) || defined(OS_CHROMEOS)) || \
267 (defined(OS_LINUX) || defined(OS_MACOSX))
268 // TODO(thestig): http://crbug.com/79837, http://crbug.com/329912
269 #define MAYBE_FindAndCopy DISABLED_FindAndCopy
271 #define MAYBE_FindAndCopy FindAndCopy
273 IN_PROC_BROWSER_TEST_F(PDFBrowserTest
, MAYBE_FindAndCopy
) {
274 ASSERT_NO_FATAL_FAILURE(Load());
275 // Verifies that find in page works.
276 ASSERT_EQ(3, ui_test_utils::FindInPage(
277 browser()->tab_strip_model()->GetActiveWebContents(),
278 base::UTF8ToUTF16("adipiscing"),
279 true, false, NULL
, NULL
));
281 // Verify that copying selected text works.
282 ui::Clipboard
* clipboard
= ui::Clipboard::GetForCurrentThread();
283 // Reset the clipboard first.
284 clipboard
->Clear(ui::CLIPBOARD_TYPE_COPY_PASTE
);
286 browser()->tab_strip_model()->GetActiveWebContents()->Copy();
287 ASSERT_NO_FATAL_FAILURE(WaitForResponse());
290 clipboard
->ReadAsciiText(ui::CLIPBOARD_TYPE_COPY_PASTE
, &text
);
291 ASSERT_EQ("adipiscing", text
);
294 const int kLoadingNumberOfParts
= 10;
296 // Tests that loading async pdfs works correctly (i.e. document fully loads).
297 // This also loads all documents that used to crash, to ensure we don't have
299 // If it flakes, reopen http://crbug.com/74548.
300 #if !defined(GOOGLE_CHROME_BUILD)
301 #define MAYBE_Loading DISABLED_Loading
303 #define MAYBE_Loading Loading
305 IN_PROC_BROWSER_TEST_P(PDFBrowserTest
, MAYBE_Loading
) {
306 ASSERT_TRUE(pdf_test_server()->InitializeAndWaitUntilReady());
308 NavigationController
* controller
=
309 &(browser()->tab_strip_model()->GetActiveWebContents()->GetController());
310 content::NotificationRegistrar registrar
;
312 content::NOTIFICATION_LOAD_STOP
,
313 content::Source
<NavigationController
>(controller
));
314 std::string base_url
= std::string("/");
316 base::FileEnumerator
file_enumerator(
317 ui_test_utils::GetTestFilePath(
318 base::FilePath(FILE_PATH_LITERAL("pdf_private")), base::FilePath()),
320 base::FileEnumerator::FILES
,
321 FILE_PATH_LITERAL("*.pdf"));
322 for (base::FilePath file_path
= file_enumerator
.Next();
324 file_path
= file_enumerator
.Next()) {
325 std::string filename
= file_path
.BaseName().MaybeAsASCII();
326 ASSERT_FALSE(filename
.empty());
328 #if defined(OS_POSIX)
329 if (filename
== "sample.pdf")
330 continue; // Crashes on Mac and Linux. http://crbug.com/63549
333 // Split the test into smaller sub-tests. Each one only loads
335 if (static_cast<int>(base::Hash(filename
) % kLoadingNumberOfParts
) !=
340 LOG(WARNING
) << "PDFBrowserTest.Loading: " << filename
;
342 GURL url
= pdf_test_server()->GetURL(base_url
+ filename
);
343 ui_test_utils::NavigateToURL(browser(), url
);
346 int last_count
= load_stop_notification_count();
347 // We might get extraneous chrome::LOAD_STOP notifications when
348 // doing async loading. This happens when the first loader is cancelled
349 // and before creating a byte-range request loader.
350 bool complete
= false;
351 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
352 browser()->tab_strip_model()->GetActiveWebContents(),
353 "window.domAutomationController.send(plugin.documentLoadComplete())",
358 // Check if the LOAD_STOP notification could have come while we run a
359 // nested message loop for the JS call.
360 if (last_count
!= load_stop_notification_count())
362 content::WaitForLoadStop(
363 browser()->tab_strip_model()->GetActiveWebContents());
368 INSTANTIATE_TEST_CASE_P(PDFTestFiles
,
370 testing::Range(0, kLoadingNumberOfParts
));
372 #if !defined(GOOGLE_CHROME_BUILD) || defined(OS_MACOSX)
373 // http://crbug.com/315160
374 #define MAYBE_Action DISABLED_Action
376 #define MAYBE_Action Action
378 IN_PROC_BROWSER_TEST_F(PDFBrowserTest
, MAYBE_Action
) {
379 ASSERT_NO_FATAL_FAILURE(Load());
381 ASSERT_TRUE(content::ExecuteScript(
382 browser()->tab_strip_model()->GetActiveWebContents(),
383 "document.getElementsByName('plugin')[0].fitToHeight();"));
385 std::string zoom1
, zoom2
;
386 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
387 browser()->tab_strip_model()->GetActiveWebContents(),
388 "window.domAutomationController.send("
389 " document.getElementsByName('plugin')[0].getZoomLevel().toString())",
392 ASSERT_TRUE(content::ExecuteScript(
393 browser()->tab_strip_model()->GetActiveWebContents(),
394 "document.getElementsByName('plugin')[0].fitToWidth();"));
396 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
397 browser()->tab_strip_model()->GetActiveWebContents(),
398 "window.domAutomationController.send("
399 " document.getElementsByName('plugin')[0].getZoomLevel().toString())",
401 ASSERT_NE(zoom1
, zoom2
);
404 // Flaky as per http://crbug.com/74549.
405 IN_PROC_BROWSER_TEST_F(PDFBrowserTest
, DISABLED_OnLoadAndReload
) {
406 ASSERT_TRUE(pdf_test_server()->InitializeAndWaitUntilReady());
408 GURL url
= pdf_test_server()->GetURL("/onload_reload.html");
409 ui_test_utils::NavigateToURL(browser(), url
);
411 content::WindowedNotificationObserver
observer(
412 content::NOTIFICATION_LOAD_STOP
,
413 content::Source
<NavigationController
>(
414 &browser()->tab_strip_model()->GetActiveWebContents()->
416 ASSERT_TRUE(content::ExecuteScript(
417 browser()->tab_strip_model()->GetActiveWebContents(),
422 browser()->tab_strip_model()->GetActiveWebContents()->