closure: fix compile error by adding missing externs
[chromium-blink-merge.git] / components / printing / test / print_web_view_helper_browsertest.cc
blobbfdc311dd9d30d1d55ece307ef1530853239cff9
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/command_line.h"
6 #include "base/run_loop.h"
7 #include "components/printing/common/print_messages.h"
8 #include "components/printing/renderer/print_web_view_helper.h"
9 #include "components/printing/test/mock_printer.h"
10 #include "components/printing/test/print_mock_render_thread.h"
11 #include "components/printing/test/print_test_content_renderer_client.h"
12 #include "content/public/renderer/render_view.h"
13 #include "content/public/test/render_view_test.h"
14 #include "ipc/ipc_listener.h"
15 #include "printing/print_job_constants.h"
16 #include "testing/gtest/include/gtest/gtest.h"
17 #include "third_party/WebKit/public/platform/WebString.h"
18 #include "third_party/WebKit/public/web/WebLocalFrame.h"
19 #include "third_party/WebKit/public/web/WebRange.h"
20 #include "third_party/WebKit/public/web/WebView.h"
22 #if defined(OS_WIN) || defined(OS_MACOSX)
23 #include "base/files/file_util.h"
24 #include "printing/image.h"
26 using blink::WebFrame;
27 using blink::WebLocalFrame;
28 using blink::WebString;
29 #endif
31 namespace printing {
33 namespace {
35 #if !defined(OS_CHROMEOS)
37 // A simple web page.
38 const char kHelloWorldHTML[] = "<body><p>Hello World!</p></body>";
40 // A simple webpage with a button to print itself with.
41 const char kPrintOnUserAction[] =
42 "<body>"
43 " <button id=\"print\" onclick=\"window.print();\">Hello World!</button>"
44 "</body>";
46 // HTML with 3 pages.
47 const char kMultipageHTML[] =
48 "<html><head><style>"
49 ".break { page-break-after: always; }"
50 "</style></head>"
51 "<body>"
52 "<div class='break'>page1</div>"
53 "<div class='break'>page2</div>"
54 "<div>page3</div>"
55 "</body></html>";
57 // A simple web page with print page size css.
58 const char kHTMLWithPageSizeCss[] =
59 "<html><head><style>"
60 "@media print {"
61 " @page {"
62 " size: 4in 4in;"
63 " }"
64 "}"
65 "</style></head>"
66 "<body>Lorem Ipsum:"
67 "</body></html>";
69 // A simple web page with print page layout css.
70 const char kHTMLWithLandscapePageCss[] =
71 "<html><head><style>"
72 "@media print {"
73 " @page {"
74 " size: landscape;"
75 " }"
76 "}"
77 "</style></head>"
78 "<body>Lorem Ipsum:"
79 "</body></html>";
81 // A longer web page.
82 const char kLongPageHTML[] =
83 "<body><img src=\"\" width=10 height=10000 /></body>";
85 // A web page to simulate the print preview page.
86 const char kPrintPreviewHTML[] =
87 "<body><p id=\"pdf-viewer\">Hello World!</p></body>";
89 void CreatePrintSettingsDictionary(base::DictionaryValue* dict) {
90 dict->SetBoolean(kSettingLandscape, false);
91 dict->SetBoolean(kSettingCollate, false);
92 dict->SetInteger(kSettingColor, GRAY);
93 dict->SetBoolean(kSettingPrintToPDF, true);
94 dict->SetInteger(kSettingDuplexMode, SIMPLEX);
95 dict->SetInteger(kSettingCopies, 1);
96 dict->SetString(kSettingDeviceName, "dummy");
97 dict->SetInteger(kPreviewUIID, 4);
98 dict->SetInteger(kPreviewRequestID, 12345);
99 dict->SetBoolean(kIsFirstRequest, true);
100 dict->SetInteger(kSettingMarginsType, DEFAULT_MARGINS);
101 dict->SetBoolean(kSettingPreviewModifiable, false);
102 dict->SetBoolean(kSettingHeaderFooterEnabled, false);
103 dict->SetBoolean(kSettingGenerateDraftData, true);
104 dict->SetBoolean(kSettingShouldPrintBackgrounds, false);
105 dict->SetBoolean(kSettingShouldPrintSelectionOnly, false);
107 #endif // !defined(OS_CHROMEOS)
109 class DidPreviewPageListener : public IPC::Listener {
110 public:
111 explicit DidPreviewPageListener(base::RunLoop* run_loop)
112 : run_loop_(run_loop) {}
114 bool OnMessageReceived(const IPC::Message& message) override {
115 if (message.type() == PrintHostMsg_MetafileReadyForPrinting::ID ||
116 message.type() == PrintHostMsg_PrintPreviewFailed::ID ||
117 message.type() == PrintHostMsg_PrintPreviewCancelled::ID)
118 run_loop_->Quit();
119 return false;
122 private:
123 base::RunLoop* const run_loop_;
124 DISALLOW_COPY_AND_ASSIGN(DidPreviewPageListener);
127 } // namespace
129 class PrintWebViewHelperTestBase : public content::RenderViewTest {
130 public:
131 PrintWebViewHelperTestBase() : print_render_thread_(NULL) {}
132 ~PrintWebViewHelperTestBase() override {}
134 protected:
135 void SetUp() override {
136 print_render_thread_ = new PrintMockRenderThread();
137 render_thread_.reset(print_render_thread_);
139 content::RenderViewTest::SetUp();
142 content::ContentRendererClient* CreateContentRendererClient() override {
143 return new PrintTestContentRendererClient();
146 void TearDown() override {
147 #if defined(LEAK_SANITIZER)
148 // Do this before shutting down V8 in RenderViewTest::TearDown().
149 // http://crbug.com/328552
150 __lsan_do_leak_check();
151 #endif
152 content::RenderViewTest::TearDown();
155 void PrintWithJavaScript() {
156 ExecuteJavaScript("window.print();");
157 ProcessPendingMessages();
159 // The renderer should be done calculating the number of rendered pages
160 // according to the specified settings defined in the mock render thread.
161 // Verify the page count is correct.
162 void VerifyPageCount(int count) {
163 #if defined(OS_CHROMEOS)
164 // The DidGetPrintedPagesCount message isn't sent on ChromeOS. Right now we
165 // always print all pages, and there are checks to that effect built into
166 // the print code.
167 #else
168 const IPC::Message* page_cnt_msg =
169 render_thread_->sink().GetUniqueMessageMatching(
170 PrintHostMsg_DidGetPrintedPagesCount::ID);
171 ASSERT_TRUE(page_cnt_msg);
172 PrintHostMsg_DidGetPrintedPagesCount::Param post_page_count_param;
173 PrintHostMsg_DidGetPrintedPagesCount::Read(page_cnt_msg,
174 &post_page_count_param);
175 EXPECT_EQ(count, get<1>(post_page_count_param));
176 #endif // defined(OS_CHROMEOS)
179 // The renderer should be done calculating the number of rendered pages
180 // according to the specified settings defined in the mock render thread.
181 // Verify the page count is correct.
182 void VerifyPreviewPageCount(int count) {
183 const IPC::Message* page_cnt_msg =
184 render_thread_->sink().GetUniqueMessageMatching(
185 PrintHostMsg_DidGetPreviewPageCount::ID);
186 ASSERT_TRUE(page_cnt_msg);
187 PrintHostMsg_DidGetPreviewPageCount::Param post_page_count_param;
188 PrintHostMsg_DidGetPreviewPageCount::Read(page_cnt_msg,
189 &post_page_count_param);
190 EXPECT_EQ(count, get<0>(post_page_count_param).page_count);
193 // Verifies whether the pages printed or not.
194 void VerifyPagesPrinted(bool printed) {
195 #if defined(OS_CHROMEOS)
196 bool did_print_msg =
197 (render_thread_->sink().GetUniqueMessageMatching(
198 PrintHostMsg_TempFileForPrintingWritten::ID) != NULL);
199 ASSERT_EQ(printed, did_print_msg);
200 #else
201 const IPC::Message* print_msg =
202 render_thread_->sink().GetUniqueMessageMatching(
203 PrintHostMsg_DidPrintPage::ID);
204 bool did_print_msg = (NULL != print_msg);
205 ASSERT_EQ(printed, did_print_msg);
206 if (printed) {
207 PrintHostMsg_DidPrintPage::Param post_did_print_page_param;
208 PrintHostMsg_DidPrintPage::Read(print_msg, &post_did_print_page_param);
209 EXPECT_EQ(0, get<0>(post_did_print_page_param).page_number);
211 #endif // defined(OS_CHROMEOS)
214 #if defined(ENABLE_BASIC_PRINTING)
215 void OnPrintPages() {
216 PrintWebViewHelper::Get(view_)->OnPrintPages();
217 ProcessPendingMessages();
219 #endif // ENABLE_BASIC_PRINTING
221 void VerifyPreviewRequest(bool requested) {
222 const IPC::Message* print_msg =
223 render_thread_->sink().GetUniqueMessageMatching(
224 PrintHostMsg_SetupScriptedPrintPreview::ID);
225 bool did_print_msg = (NULL != print_msg);
226 ASSERT_EQ(requested, did_print_msg);
229 void OnPrintPreview(const base::DictionaryValue& dict) {
230 PrintWebViewHelper* print_web_view_helper = PrintWebViewHelper::Get(view_);
231 print_web_view_helper->OnInitiatePrintPreview(false);
232 base::RunLoop run_loop;
233 DidPreviewPageListener filter(&run_loop);
234 render_thread_->sink().AddFilter(&filter);
235 print_web_view_helper->OnPrintPreview(dict);
236 run_loop.Run();
237 render_thread_->sink().RemoveFilter(&filter);
240 void OnPrintForPrintPreview(const base::DictionaryValue& dict) {
241 PrintWebViewHelper::Get(view_)->OnPrintForPrintPreview(dict);
242 ProcessPendingMessages();
245 // Naked pointer as ownership is with content::RenderViewTest::render_thread_.
246 PrintMockRenderThread* print_render_thread_;
248 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelperTestBase);
251 class PrintWebViewHelperTest : public PrintWebViewHelperTestBase {
252 public:
253 PrintWebViewHelperTest() {}
254 ~PrintWebViewHelperTest() override {}
256 void SetUp() override { PrintWebViewHelperTestBase::SetUp(); }
258 protected:
259 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelperTest);
262 // This tests only for platforms without print preview.
263 #if !defined(ENABLE_PRINT_PREVIEW)
264 // Tests that the renderer blocks window.print() calls if they occur too
265 // frequently.
266 TEST_F(PrintWebViewHelperTest, BlockScriptInitiatedPrinting) {
267 // Pretend user will cancel printing.
268 print_render_thread_->set_print_dialog_user_response(false);
269 // Try to print with window.print() a few times.
270 PrintWithJavaScript();
271 PrintWithJavaScript();
272 PrintWithJavaScript();
273 VerifyPagesPrinted(false);
275 // Pretend user will print. (but printing is blocked.)
276 print_render_thread_->set_print_dialog_user_response(true);
277 PrintWithJavaScript();
278 VerifyPagesPrinted(false);
280 // Unblock script initiated printing and verify printing works.
281 PrintWebViewHelper::Get(view_)->scripting_throttler_.Reset();
282 print_render_thread_->printer()->ResetPrinter();
283 PrintWithJavaScript();
284 VerifyPageCount(1);
285 VerifyPagesPrinted(true);
288 // Tests that the renderer always allows window.print() calls if they are user
289 // initiated.
290 TEST_F(PrintWebViewHelperTest, AllowUserOriginatedPrinting) {
291 // Pretend user will cancel printing.
292 print_render_thread_->set_print_dialog_user_response(false);
293 // Try to print with window.print() a few times.
294 PrintWithJavaScript();
295 PrintWithJavaScript();
296 PrintWithJavaScript();
297 VerifyPagesPrinted(false);
299 // Pretend user will print. (but printing is blocked.)
300 print_render_thread_->set_print_dialog_user_response(true);
301 PrintWithJavaScript();
302 VerifyPagesPrinted(false);
304 // Try again as if user initiated, without resetting the print count.
305 print_render_thread_->printer()->ResetPrinter();
306 LoadHTML(kPrintOnUserAction);
307 gfx::Size new_size(200, 100);
308 Resize(new_size, gfx::Rect(), false);
310 gfx::Rect bounds = GetElementBounds("print");
311 EXPECT_FALSE(bounds.IsEmpty());
312 blink::WebMouseEvent mouse_event;
313 mouse_event.type = blink::WebInputEvent::MouseDown;
314 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
315 mouse_event.x = bounds.CenterPoint().x();
316 mouse_event.y = bounds.CenterPoint().y();
317 mouse_event.clickCount = 1;
318 SendWebMouseEvent(mouse_event);
319 mouse_event.type = blink::WebInputEvent::MouseUp;
320 SendWebMouseEvent(mouse_event);
321 ProcessPendingMessages();
323 VerifyPageCount(1);
324 VerifyPagesPrinted(true);
327 // Duplicate of OnPrintPagesTest only using javascript to print.
328 TEST_F(PrintWebViewHelperTest, PrintWithJavascript) {
329 PrintWithJavaScript();
331 VerifyPageCount(1);
332 VerifyPagesPrinted(true);
334 #endif // !ENABLE_PRINT_PREVIEW
336 #if defined(ENABLE_BASIC_PRINTING)
337 // Tests that printing pages work and sending and receiving messages through
338 // that channel all works.
339 TEST_F(PrintWebViewHelperTest, OnPrintPages) {
340 LoadHTML(kHelloWorldHTML);
341 OnPrintPages();
343 VerifyPageCount(1);
344 VerifyPagesPrinted(true);
346 #endif // ENABLE_BASIC_PRINTING
348 #if defined(OS_MACOSX) && defined(ENABLE_BASIC_PRINTING)
349 // TODO(estade): I don't think this test is worth porting to Linux. We will have
350 // to rip out and replace most of the IPC code if we ever plan to improve
351 // printing, and the comment below by sverrir suggests that it doesn't do much
352 // for us anyway.
353 TEST_F(PrintWebViewHelperTest, PrintWithIframe) {
354 // Document that populates an iframe.
355 const char html[] =
356 "<html><body>Lorem Ipsum:"
357 "<iframe name=\"sub1\" id=\"sub1\"></iframe><script>"
358 " document.write(frames['sub1'].name);"
359 " frames['sub1'].document.write("
360 " '<p>Cras tempus ante eu felis semper luctus!</p>');"
361 " frames['sub1'].document.close();"
362 "</script></body></html>";
364 LoadHTML(html);
366 // Find the frame and set it as the focused one. This should mean that that
367 // the printout should only contain the contents of that frame.
368 WebFrame* sub1_frame =
369 view_->GetWebView()->findFrameByName(WebString::fromUTF8("sub1"));
370 ASSERT_TRUE(sub1_frame);
371 view_->GetWebView()->setFocusedFrame(sub1_frame);
372 ASSERT_NE(view_->GetWebView()->focusedFrame(),
373 view_->GetWebView()->mainFrame());
375 // Initiate printing.
376 OnPrintPages();
377 VerifyPagesPrinted(true);
379 // Verify output through MockPrinter.
380 const MockPrinter* printer(print_render_thread_->printer());
381 ASSERT_EQ(1, printer->GetPrintedPages());
382 const Image& image1(printer->GetPrintedPage(0)->image());
384 // TODO(sverrir): Figure out a way to improve this test to actually print
385 // only the content of the iframe. Currently image1 will contain the full
386 // page.
387 EXPECT_NE(0, image1.size().width());
388 EXPECT_NE(0, image1.size().height());
390 #endif // OS_MACOSX && ENABLE_BASIC_PRINTING
392 // Tests if we can print a page and verify its results.
393 // This test prints HTML pages into a pseudo printer and check their outputs,
394 // i.e. a simplified version of the PrintingLayoutTextTest UI test.
395 namespace {
396 // Test cases used in this test.
397 struct TestPageData {
398 const char* page;
399 size_t printed_pages;
400 int width;
401 int height;
402 const char* checksum;
403 const wchar_t* file;
406 #if defined(OS_WIN) || defined(OS_MACOSX)
407 const TestPageData kTestPages[] = {
409 "<html>"
410 "<head>"
411 "<meta"
412 " http-equiv=\"Content-Type\""
413 " content=\"text/html; charset=utf-8\"/>"
414 "<title>Test 1</title>"
415 "</head>"
416 "<body style=\"background-color: white;\">"
417 "<p style=\"font-family: arial;\">Hello World!</p>"
418 "</body>",
419 #if defined(OS_MACOSX)
420 // Mac printing code compensates for the WebKit scale factor while
421 // generating
422 // the metafile, so we expect smaller pages.
424 600,
425 780,
426 #else
428 675,
429 900,
430 #endif
431 NULL,
432 NULL,
435 #endif // defined(OS_WIN) || defined(OS_MACOSX)
436 } // namespace
438 // TODO(estade): need to port MockPrinter to get this on Linux. This involves
439 // hooking up Cairo to read a pdf stream, or accessing the cairo surface in the
440 // metafile directly.
441 // Same for printing via PDF on Windows.
442 #if defined(OS_MACOSX) && defined(ENABLE_BASIC_PRINTING)
443 TEST_F(PrintWebViewHelperTest, PrintLayoutTest) {
444 bool baseline = false;
446 EXPECT_TRUE(print_render_thread_->printer() != NULL);
447 for (size_t i = 0; i < arraysize(kTestPages); ++i) {
448 // Load an HTML page and print it.
449 LoadHTML(kTestPages[i].page);
450 OnPrintPages();
451 VerifyPagesPrinted(true);
453 // MockRenderThread::Send() just calls MockRenderThread::OnReceived().
454 // So, all IPC messages sent in the above RenderView::OnPrintPages() call
455 // has been handled by the MockPrinter object, i.e. this printing job
456 // has been already finished.
457 // So, we can start checking the output pages of this printing job.
458 // Retrieve the number of pages actually printed.
459 size_t pages = print_render_thread_->printer()->GetPrintedPages();
460 EXPECT_EQ(kTestPages[i].printed_pages, pages);
462 // Retrieve the width and height of the output page.
463 int width = print_render_thread_->printer()->GetWidth(0);
464 int height = print_render_thread_->printer()->GetHeight(0);
466 // Check with margin for error. This has been failing with a one pixel
467 // offset on our buildbot.
468 const int kErrorMargin = 5; // 5%
469 EXPECT_GT(kTestPages[i].width * (100 + kErrorMargin) / 100, width);
470 EXPECT_LT(kTestPages[i].width * (100 - kErrorMargin) / 100, width);
471 EXPECT_GT(kTestPages[i].height * (100 + kErrorMargin) / 100, height);
472 EXPECT_LT(kTestPages[i].height * (100 - kErrorMargin) / 100, height);
474 // Retrieve the checksum of the bitmap data from the pseudo printer and
475 // compare it with the expected result.
476 std::string bitmap_actual;
477 EXPECT_TRUE(
478 print_render_thread_->printer()->GetBitmapChecksum(0, &bitmap_actual));
479 if (kTestPages[i].checksum)
480 EXPECT_EQ(kTestPages[i].checksum, bitmap_actual);
482 if (baseline) {
483 // Save the source data and the bitmap data into temporary files to
484 // create base-line results.
485 base::FilePath source_path;
486 base::CreateTemporaryFile(&source_path);
487 print_render_thread_->printer()->SaveSource(0, source_path);
489 base::FilePath bitmap_path;
490 base::CreateTemporaryFile(&bitmap_path);
491 print_render_thread_->printer()->SaveBitmap(0, bitmap_path);
495 #endif // OS_MACOSX && ENABLE_BASIC_PRINTING
497 // These print preview tests do not work on Chrome OS yet.
498 #if !defined(OS_CHROMEOS)
499 class PrintWebViewHelperPreviewTest : public PrintWebViewHelperTestBase {
500 public:
501 PrintWebViewHelperPreviewTest() {}
502 ~PrintWebViewHelperPreviewTest() override {}
504 protected:
505 void VerifyPrintPreviewCancelled(bool did_cancel) {
506 bool print_preview_cancelled =
507 (render_thread_->sink().GetUniqueMessageMatching(
508 PrintHostMsg_PrintPreviewCancelled::ID) != NULL);
509 EXPECT_EQ(did_cancel, print_preview_cancelled);
512 void VerifyPrintPreviewFailed(bool did_fail) {
513 bool print_preview_failed =
514 (render_thread_->sink().GetUniqueMessageMatching(
515 PrintHostMsg_PrintPreviewFailed::ID) != NULL);
516 EXPECT_EQ(did_fail, print_preview_failed);
519 void VerifyPrintPreviewGenerated(bool generated_preview) {
520 const IPC::Message* preview_msg =
521 render_thread_->sink().GetUniqueMessageMatching(
522 PrintHostMsg_MetafileReadyForPrinting::ID);
523 bool did_get_preview_msg = (NULL != preview_msg);
524 ASSERT_EQ(generated_preview, did_get_preview_msg);
525 if (did_get_preview_msg) {
526 PrintHostMsg_MetafileReadyForPrinting::Param preview_param;
527 PrintHostMsg_MetafileReadyForPrinting::Read(preview_msg, &preview_param);
528 EXPECT_NE(0, get<0>(preview_param).document_cookie);
529 EXPECT_NE(0, get<0>(preview_param).expected_pages_count);
530 EXPECT_NE(0U, get<0>(preview_param).data_size);
534 void VerifyPrintFailed(bool did_fail) {
535 bool print_failed = (render_thread_->sink().GetUniqueMessageMatching(
536 PrintHostMsg_PrintingFailed::ID) != NULL);
537 EXPECT_EQ(did_fail, print_failed);
540 void VerifyPrintPreviewInvalidPrinterSettings(bool settings_invalid) {
541 bool print_preview_invalid_printer_settings =
542 (render_thread_->sink().GetUniqueMessageMatching(
543 PrintHostMsg_PrintPreviewInvalidPrinterSettings::ID) != NULL);
544 EXPECT_EQ(settings_invalid, print_preview_invalid_printer_settings);
547 // |page_number| is 0-based.
548 void VerifyDidPreviewPage(bool generate_draft_pages, int page_number) {
549 bool msg_found = false;
550 size_t msg_count = render_thread_->sink().message_count();
551 for (size_t i = 0; i < msg_count; ++i) {
552 const IPC::Message* msg = render_thread_->sink().GetMessageAt(i);
553 if (msg->type() == PrintHostMsg_DidPreviewPage::ID) {
554 PrintHostMsg_DidPreviewPage::Param page_param;
555 PrintHostMsg_DidPreviewPage::Read(msg, &page_param);
556 if (get<0>(page_param).page_number == page_number) {
557 msg_found = true;
558 if (generate_draft_pages)
559 EXPECT_NE(0U, get<0>(page_param).data_size);
560 else
561 EXPECT_EQ(0U, get<0>(page_param).data_size);
562 break;
566 ASSERT_EQ(generate_draft_pages, msg_found);
569 void VerifyDefaultPageLayout(int content_width,
570 int content_height,
571 int margin_top,
572 int margin_bottom,
573 int margin_left,
574 int margin_right,
575 bool page_has_print_css) {
576 const IPC::Message* default_page_layout_msg =
577 render_thread_->sink().GetUniqueMessageMatching(
578 PrintHostMsg_DidGetDefaultPageLayout::ID);
579 bool did_get_default_page_layout_msg = (NULL != default_page_layout_msg);
580 if (did_get_default_page_layout_msg) {
581 PrintHostMsg_DidGetDefaultPageLayout::Param param;
582 PrintHostMsg_DidGetDefaultPageLayout::Read(default_page_layout_msg,
583 &param);
584 EXPECT_EQ(content_width, get<0>(param).content_width);
585 EXPECT_EQ(content_height, get<0>(param).content_height);
586 EXPECT_EQ(margin_top, get<0>(param).margin_top);
587 EXPECT_EQ(margin_right, get<0>(param).margin_right);
588 EXPECT_EQ(margin_left, get<0>(param).margin_left);
589 EXPECT_EQ(margin_bottom, get<0>(param).margin_bottom);
590 EXPECT_EQ(page_has_print_css, get<2>(param));
594 DISALLOW_COPY_AND_ASSIGN(PrintWebViewHelperPreviewTest);
597 #if defined(ENABLE_PRINT_PREVIEW)
598 TEST_F(PrintWebViewHelperPreviewTest, BlockScriptInitiatedPrinting) {
599 LoadHTML(kHelloWorldHTML);
600 PrintWebViewHelper* print_web_view_helper = PrintWebViewHelper::Get(view_);
601 print_web_view_helper->SetScriptedPrintBlocked(true);
602 PrintWithJavaScript();
603 VerifyPreviewRequest(false);
605 print_web_view_helper->SetScriptedPrintBlocked(false);
606 PrintWithJavaScript();
607 VerifyPreviewRequest(true);
610 TEST_F(PrintWebViewHelperPreviewTest, PrintWithJavaScript) {
611 LoadHTML(kPrintOnUserAction);
612 gfx::Size new_size(200, 100);
613 Resize(new_size, gfx::Rect(), false);
615 gfx::Rect bounds = GetElementBounds("print");
616 EXPECT_FALSE(bounds.IsEmpty());
617 blink::WebMouseEvent mouse_event;
618 mouse_event.type = blink::WebInputEvent::MouseDown;
619 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
620 mouse_event.x = bounds.CenterPoint().x();
621 mouse_event.y = bounds.CenterPoint().y();
622 mouse_event.clickCount = 1;
623 SendWebMouseEvent(mouse_event);
624 mouse_event.type = blink::WebInputEvent::MouseUp;
625 SendWebMouseEvent(mouse_event);
627 VerifyPreviewRequest(true);
629 #endif // ENABLE_PRINT_PREVIEW
631 // Tests that print preview work and sending and receiving messages through
632 // that channel all works.
633 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreview) {
634 LoadHTML(kHelloWorldHTML);
636 // Fill in some dummy values.
637 base::DictionaryValue dict;
638 CreatePrintSettingsDictionary(&dict);
639 OnPrintPreview(dict);
641 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
642 VerifyDefaultPageLayout(540, 720, 36, 36, 36, 36, false);
643 VerifyPrintPreviewCancelled(false);
644 VerifyPrintPreviewFailed(false);
645 VerifyPrintPreviewGenerated(true);
646 VerifyPagesPrinted(false);
649 TEST_F(PrintWebViewHelperPreviewTest, PrintPreviewHTMLWithPageMarginsCss) {
650 // A simple web page with print margins css.
651 const char kHTMLWithPageMarginsCss[] =
652 "<html><head><style>"
653 "@media print {"
654 " @page {"
655 " margin: 3in 1in 2in 0.3in;"
656 " }"
658 "</style></head>"
659 "<body>Lorem Ipsum:"
660 "</body></html>";
661 LoadHTML(kHTMLWithPageMarginsCss);
663 // Fill in some dummy values.
664 base::DictionaryValue dict;
665 CreatePrintSettingsDictionary(&dict);
666 dict.SetBoolean(kSettingPrintToPDF, false);
667 dict.SetInteger(kSettingMarginsType, DEFAULT_MARGINS);
668 OnPrintPreview(dict);
670 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
671 VerifyDefaultPageLayout(519, 432, 216, 144, 21, 72, false);
672 VerifyPrintPreviewCancelled(false);
673 VerifyPrintPreviewFailed(false);
674 VerifyPrintPreviewGenerated(true);
675 VerifyPagesPrinted(false);
678 // Test to verify that print preview ignores print media css when non-default
679 // margin is selected.
680 TEST_F(PrintWebViewHelperPreviewTest, NonDefaultMarginsSelectedIgnorePrintCss) {
681 LoadHTML(kHTMLWithPageSizeCss);
683 // Fill in some dummy values.
684 base::DictionaryValue dict;
685 CreatePrintSettingsDictionary(&dict);
686 dict.SetBoolean(kSettingPrintToPDF, false);
687 dict.SetInteger(kSettingMarginsType, NO_MARGINS);
688 OnPrintPreview(dict);
690 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
691 VerifyDefaultPageLayout(612, 792, 0, 0, 0, 0, true);
692 VerifyPrintPreviewCancelled(false);
693 VerifyPrintPreviewFailed(false);
694 VerifyPrintPreviewGenerated(true);
695 VerifyPagesPrinted(false);
698 // Test to verify that print preview honor print media size css when
699 // PRINT_TO_PDF is selected and doesn't fit to printer default paper size.
700 TEST_F(PrintWebViewHelperPreviewTest, PrintToPDFSelectedHonorPrintCss) {
701 LoadHTML(kHTMLWithPageSizeCss);
703 // Fill in some dummy values.
704 base::DictionaryValue dict;
705 CreatePrintSettingsDictionary(&dict);
706 dict.SetBoolean(kSettingPrintToPDF, true);
707 dict.SetInteger(kSettingMarginsType, PRINTABLE_AREA_MARGINS);
708 OnPrintPreview(dict);
710 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
711 // Since PRINT_TO_PDF is selected, pdf page size is equal to print media page
712 // size.
713 VerifyDefaultPageLayout(252, 252, 18, 18, 18, 18, true);
714 VerifyPrintPreviewCancelled(false);
715 VerifyPrintPreviewFailed(false);
718 // Test to verify that print preview honor print margin css when PRINT_TO_PDF
719 // is selected and doesn't fit to printer default paper size.
720 TEST_F(PrintWebViewHelperPreviewTest, PrintToPDFSelectedHonorPageMarginsCss) {
721 // A simple web page with print margins css.
722 const char kHTMLWithPageCss[] =
723 "<html><head><style>"
724 "@media print {"
725 " @page {"
726 " margin: 3in 1in 2in 0.3in;"
727 " size: 14in 14in;"
728 " }"
730 "</style></head>"
731 "<body>Lorem Ipsum:"
732 "</body></html>";
733 LoadHTML(kHTMLWithPageCss);
735 // Fill in some dummy values.
736 base::DictionaryValue dict;
737 CreatePrintSettingsDictionary(&dict);
738 dict.SetBoolean(kSettingPrintToPDF, true);
739 dict.SetInteger(kSettingMarginsType, DEFAULT_MARGINS);
740 OnPrintPreview(dict);
742 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
743 // Since PRINT_TO_PDF is selected, pdf page size is equal to print media page
744 // size.
745 VerifyDefaultPageLayout(915, 648, 216, 144, 21, 72, true);
746 VerifyPrintPreviewCancelled(false);
747 VerifyPrintPreviewFailed(false);
750 // Test to verify that print preview workflow center the html page contents to
751 // fit the page size.
752 TEST_F(PrintWebViewHelperPreviewTest, PrintPreviewCenterToFitPage) {
753 LoadHTML(kHTMLWithPageSizeCss);
755 // Fill in some dummy values.
756 base::DictionaryValue dict;
757 CreatePrintSettingsDictionary(&dict);
758 dict.SetBoolean(kSettingPrintToPDF, false);
759 dict.SetInteger(kSettingMarginsType, DEFAULT_MARGINS);
760 OnPrintPreview(dict);
762 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
763 VerifyDefaultPageLayout(216, 216, 288, 288, 198, 198, true);
764 VerifyPrintPreviewCancelled(false);
765 VerifyPrintPreviewFailed(false);
766 VerifyPrintPreviewGenerated(true);
769 // Test to verify that print preview workflow scale the html page contents to
770 // fit the page size.
771 TEST_F(PrintWebViewHelperPreviewTest, PrintPreviewShrinkToFitPage) {
772 // A simple web page with print margins css.
773 const char kHTMLWithPageCss[] =
774 "<html><head><style>"
775 "@media print {"
776 " @page {"
777 " size: 15in 17in;"
778 " }"
780 "</style></head>"
781 "<body>Lorem Ipsum:"
782 "</body></html>";
783 LoadHTML(kHTMLWithPageCss);
785 // Fill in some dummy values.
786 base::DictionaryValue dict;
787 CreatePrintSettingsDictionary(&dict);
788 dict.SetBoolean(kSettingPrintToPDF, false);
789 dict.SetInteger(kSettingMarginsType, DEFAULT_MARGINS);
790 OnPrintPreview(dict);
792 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
793 VerifyDefaultPageLayout(571, 652, 69, 71, 20, 21, true);
794 VerifyPrintPreviewCancelled(false);
795 VerifyPrintPreviewFailed(false);
798 // Test to verify that print preview workflow honor the orientation settings
799 // specified in css.
800 TEST_F(PrintWebViewHelperPreviewTest, PrintPreviewHonorsOrientationCss) {
801 LoadHTML(kHTMLWithLandscapePageCss);
803 // Fill in some dummy values.
804 base::DictionaryValue dict;
805 CreatePrintSettingsDictionary(&dict);
806 dict.SetBoolean(kSettingPrintToPDF, false);
807 dict.SetInteger(kSettingMarginsType, NO_MARGINS);
808 OnPrintPreview(dict);
810 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
811 VerifyDefaultPageLayout(792, 612, 0, 0, 0, 0, true);
812 VerifyPrintPreviewCancelled(false);
813 VerifyPrintPreviewFailed(false);
816 // Test to verify that print preview workflow honors the orientation settings
817 // specified in css when PRINT_TO_PDF is selected.
818 TEST_F(PrintWebViewHelperPreviewTest, PrintToPDFSelectedHonorOrientationCss) {
819 LoadHTML(kHTMLWithLandscapePageCss);
821 // Fill in some dummy values.
822 base::DictionaryValue dict;
823 CreatePrintSettingsDictionary(&dict);
824 dict.SetBoolean(kSettingPrintToPDF, true);
825 dict.SetInteger(kSettingMarginsType, CUSTOM_MARGINS);
826 OnPrintPreview(dict);
828 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
829 VerifyDefaultPageLayout(748, 568, 21, 23, 21, 23, true);
830 VerifyPrintPreviewCancelled(false);
831 VerifyPrintPreviewFailed(false);
834 // Test to verify that complete metafile is generated for a subset of pages
835 // without creating draft pages.
836 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewForSelectedPages) {
837 LoadHTML(kMultipageHTML);
839 // Fill in some dummy values.
840 base::DictionaryValue dict;
841 CreatePrintSettingsDictionary(&dict);
843 // Set a page range and update the dictionary to generate only the complete
844 // metafile with the selected pages. Page numbers used in the dictionary
845 // are 1-based.
846 base::DictionaryValue* page_range = new base::DictionaryValue();
847 page_range->SetInteger(kSettingPageRangeFrom, 2);
848 page_range->SetInteger(kSettingPageRangeTo, 3);
850 base::ListValue* page_range_array = new base::ListValue();
851 page_range_array->Append(page_range);
853 dict.Set(kSettingPageRange, page_range_array);
854 dict.SetBoolean(kSettingGenerateDraftData, false);
856 OnPrintPreview(dict);
858 VerifyDidPreviewPage(false, 0);
859 VerifyDidPreviewPage(false, 1);
860 VerifyDidPreviewPage(false, 2);
861 VerifyPreviewPageCount(3);
862 VerifyPrintPreviewCancelled(false);
863 VerifyPrintPreviewFailed(false);
864 VerifyPrintPreviewGenerated(true);
865 VerifyPagesPrinted(false);
868 // Test to verify that preview generated only for one page.
869 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewForSelectedText) {
870 LoadHTML(kMultipageHTML);
871 GetMainFrame()->selectRange(
872 blink::WebRange::fromDocumentRange(GetMainFrame(), 1, 3));
874 // Fill in some dummy values.
875 base::DictionaryValue dict;
876 CreatePrintSettingsDictionary(&dict);
877 dict.SetBoolean(kSettingShouldPrintSelectionOnly, true);
879 OnPrintPreview(dict);
881 VerifyPreviewPageCount(1);
882 VerifyPrintPreviewCancelled(false);
883 VerifyPrintPreviewFailed(false);
884 VerifyPrintPreviewGenerated(true);
885 VerifyPagesPrinted(false);
888 // Tests that print preview fails and receiving error messages through
889 // that channel all works.
890 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewFail) {
891 LoadHTML(kHelloWorldHTML);
893 // An empty dictionary should fail.
894 base::DictionaryValue empty_dict;
895 OnPrintPreview(empty_dict);
897 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
898 VerifyPrintPreviewCancelled(false);
899 VerifyPrintPreviewFailed(true);
900 VerifyPrintPreviewGenerated(false);
901 VerifyPagesPrinted(false);
904 // Tests that cancelling print preview works.
905 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewCancel) {
906 LoadHTML(kLongPageHTML);
908 const int kCancelPage = 3;
909 print_render_thread_->set_print_preview_cancel_page_number(kCancelPage);
910 // Fill in some dummy values.
911 base::DictionaryValue dict;
912 CreatePrintSettingsDictionary(&dict);
913 OnPrintPreview(dict);
915 EXPECT_EQ(kCancelPage, print_render_thread_->print_preview_pages_remaining());
916 VerifyPrintPreviewCancelled(true);
917 VerifyPrintPreviewFailed(false);
918 VerifyPrintPreviewGenerated(false);
919 VerifyPagesPrinted(false);
922 // Tests that printing from print preview works and sending and receiving
923 // messages through that channel all works.
924 TEST_F(PrintWebViewHelperPreviewTest, OnPrintForPrintPreview) {
925 LoadHTML(kPrintPreviewHTML);
927 // Fill in some dummy values.
928 base::DictionaryValue dict;
929 CreatePrintSettingsDictionary(&dict);
930 OnPrintForPrintPreview(dict);
932 VerifyPrintFailed(false);
933 VerifyPagesPrinted(true);
936 // Tests that printing from print preview fails and receiving error messages
937 // through that channel all works.
938 TEST_F(PrintWebViewHelperPreviewTest, OnPrintForPrintPreviewFail) {
939 LoadHTML(kPrintPreviewHTML);
941 // An empty dictionary should fail.
942 base::DictionaryValue empty_dict;
943 OnPrintForPrintPreview(empty_dict);
945 VerifyPagesPrinted(false);
948 // Tests that when default printer has invalid printer settings, print preview
949 // receives error message.
950 TEST_F(PrintWebViewHelperPreviewTest,
951 OnPrintPreviewUsingInvalidPrinterSettings) {
952 LoadHTML(kPrintPreviewHTML);
954 // Set mock printer to provide invalid settings.
955 print_render_thread_->printer()->UseInvalidSettings();
957 // Fill in some dummy values.
958 base::DictionaryValue dict;
959 CreatePrintSettingsDictionary(&dict);
960 OnPrintPreview(dict);
962 // We should have received invalid printer settings from |printer_|.
963 VerifyPrintPreviewInvalidPrinterSettings(true);
964 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
966 // It should receive the invalid printer settings message only.
967 VerifyPrintPreviewFailed(false);
968 VerifyPrintPreviewGenerated(false);
971 // Tests that when the selected printer has invalid page settings, print preview
972 // receives error message.
973 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewUsingInvalidPageSize) {
974 LoadHTML(kPrintPreviewHTML);
976 print_render_thread_->printer()->UseInvalidPageSize();
978 base::DictionaryValue dict;
979 CreatePrintSettingsDictionary(&dict);
980 OnPrintPreview(dict);
982 VerifyPrintPreviewInvalidPrinterSettings(true);
983 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
985 // It should receive the invalid printer settings message only.
986 VerifyPrintPreviewFailed(false);
987 VerifyPrintPreviewGenerated(false);
990 // Tests that when the selected printer has invalid content settings, print
991 // preview receives error message.
992 TEST_F(PrintWebViewHelperPreviewTest, OnPrintPreviewUsingInvalidContentSize) {
993 LoadHTML(kPrintPreviewHTML);
995 print_render_thread_->printer()->UseInvalidContentSize();
997 base::DictionaryValue dict;
998 CreatePrintSettingsDictionary(&dict);
999 OnPrintPreview(dict);
1001 VerifyPrintPreviewInvalidPrinterSettings(true);
1002 EXPECT_EQ(0, print_render_thread_->print_preview_pages_remaining());
1004 // It should receive the invalid printer settings message only.
1005 VerifyPrintPreviewFailed(false);
1006 VerifyPrintPreviewGenerated(false);
1009 TEST_F(PrintWebViewHelperPreviewTest,
1010 OnPrintForPrintPreviewUsingInvalidPrinterSettings) {
1011 LoadHTML(kPrintPreviewHTML);
1013 // Set mock printer to provide invalid settings.
1014 print_render_thread_->printer()->UseInvalidSettings();
1016 // Fill in some dummy values.
1017 base::DictionaryValue dict;
1018 CreatePrintSettingsDictionary(&dict);
1019 OnPrintForPrintPreview(dict);
1021 VerifyPrintFailed(true);
1022 VerifyPagesPrinted(false);
1025 #endif // !defined(OS_CHROMEOS)
1027 } // namespace printing