1 // Copyright 2014 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.
14 #include "base/bind.h"
15 #include "base/callback.h"
16 #include "base/files/file.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/logging.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/path_service.h"
24 #include "base/run_loop.h"
25 #include "base/strings/string_split.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "chrome/browser/printing/print_preview_dialog_controller.h"
28 #include "chrome/browser/ui/browser.h"
29 #include "chrome/browser/ui/browser_commands.h"
30 #include "chrome/browser/ui/tabs/tab_strip_model.h"
31 #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
32 #include "chrome/common/chrome_paths.h"
33 #include "chrome/test/base/in_process_browser_test.h"
34 #include "chrome/test/base/ui_test_utils.h"
35 #include "components/printing/common/print_messages.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/browser/web_ui_message_handler.h"
38 #include "content/public/test/browser_test_utils.h"
39 #include "ipc/ipc_message_macros.h"
40 #include "net/base/filename_util.h"
42 #include "printing/pdf_render_settings.h"
43 #include "printing/units.h"
44 #include "ui/gfx/codec/png_codec.h"
45 #include "ui/gfx/geometry/rect.h"
53 using content::WebContents
;
54 using content::WebContentsObserver
;
58 // Number of color channels in a BGRA bitmap.
59 const int kColorChannels
= 4;
62 // Every state is used when the document is a non-PDF source. When the source is
63 // a PDF, kWaitingToSendSaveAsPDF, kWaitingToSendPageNumbers, and
64 // kWaitingForFinalMessage are the only states used.
66 // Waiting for the first message so the program can select Save as PDF
67 kWaitingToSendSaveAsPdf
= 0,
68 // Waiting for the second message so the test can set the layout
69 kWaitingToSendLayoutSettings
= 1,
70 // Waiting for the third message so the test can set the page numbers
71 kWaitingToSendPageNumbers
= 2,
72 // Waiting for the forth message so the test can set the headers checkbox
73 kWaitingToSendHeadersAndFooters
= 3,
74 // Waiting for the fifth message so the test can set the background checkbox
75 kWaitingToSendBackgroundColorsAndImages
= 4,
76 // Waiting for the sixth message so the test can set the margins combobox
77 kWaitingToSendMargins
= 5,
78 // Waiting for the final message so the program can save to PDF.
79 kWaitingForFinalMessage
= 6,
82 // Settings for print preview. It reflects the current options provided by
83 // print preview. If more options are added, more states should be added and
84 // there should be more settings added to this struct.
85 struct PrintPreviewSettings
{
86 PrintPreviewSettings(bool is_portrait
,
87 const std::string
& page_numbers
,
88 bool headers_and_footers
,
89 bool background_colors_and_images
,
92 : is_portrait(is_portrait
),
93 page_numbers(page_numbers
),
94 headers_and_footers(headers_and_footers
),
95 background_colors_and_images(background_colors_and_images
),
97 source_is_pdf(source_is_pdf
) {}
100 std::string page_numbers
;
101 bool headers_and_footers
;
102 bool background_colors_and_images
;
107 // Observes the print preview webpage. Once it observes the PreviewPageCount
108 // message, will send a sequence of commands to the print preview dialog and
109 // change the settings of the preview dialog.
110 class PrintPreviewObserver
: public WebContentsObserver
{
112 PrintPreviewObserver(Browser
* browser
,
114 const base::FilePath
& pdf_file_save_path
)
115 : WebContentsObserver(dialog
),
117 state_(kWaitingToSendSaveAsPdf
),
118 failed_setting_("None"),
119 pdf_file_save_path_(pdf_file_save_path
) {}
121 ~PrintPreviewObserver() override
{}
123 // Sets closure for the observer so that it can end the loop.
124 void set_quit_closure(const base::Closure
&closure
) {
125 quit_closure_
= closure
;
128 // Actually stops the message loop so that the test can proceed.
130 base::MessageLoop::current()->PostTask(FROM_HERE
, quit_closure_
);
133 bool OnMessageReceived(const IPC::Message
& message
) override
{
134 IPC_BEGIN_MESSAGE_MAP(PrintPreviewObserver
, message
)
135 IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount
,
136 OnDidGetPreviewPageCount
)
137 IPC_END_MESSAGE_MAP();
141 // Gets the web contents for the print preview dialog so that the UI and
142 // other elements can be accessed.
143 WebContents
* GetDialog() {
144 WebContents
* tab
= browser_
->tab_strip_model()->GetActiveWebContents();
145 PrintPreviewDialogController
* dialog_controller
=
146 PrintPreviewDialogController::GetInstance();
147 return dialog_controller
->GetPrintPreviewForContents(tab
);
150 // Gets the PrintPreviewUI so that certain elements can be accessed.
151 PrintPreviewUI
* GetUI() {
152 return static_cast<PrintPreviewUI
*>(
153 GetDialog()->GetWebUI()->GetController());
156 // Calls native_layer.onManipulateSettingsForTest() and sends a dictionary
157 // value containing the type of setting and the value to set that settings
159 void ManipulatePreviewSettings() {
160 base::DictionaryValue script_argument
;
162 if (state_
== kWaitingToSendSaveAsPdf
) {
163 script_argument
.SetBoolean("selectSaveAsPdfDestination", true);
164 state_
= settings_
->source_is_pdf
?
165 kWaitingToSendPageNumbers
: kWaitingToSendLayoutSettings
;
166 failed_setting_
= "Save as PDF";
167 } else if (state_
== kWaitingToSendLayoutSettings
) {
168 script_argument
.SetBoolean("layoutSettings.portrait",
169 settings_
->is_portrait
);
170 state_
= kWaitingToSendPageNumbers
;
171 failed_setting_
= "Layout Settings";
172 } else if (state_
== kWaitingToSendPageNumbers
) {
173 script_argument
.SetString("pageRange", settings_
->page_numbers
);
174 state_
= settings_
->source_is_pdf
?
175 kWaitingForFinalMessage
: kWaitingToSendHeadersAndFooters
;
176 failed_setting_
= "Page Range";
177 } else if (state_
== kWaitingToSendHeadersAndFooters
) {
178 script_argument
.SetBoolean("headersAndFooters",
179 settings_
->headers_and_footers
);
180 state_
= kWaitingToSendBackgroundColorsAndImages
;
181 failed_setting_
= "Headers and Footers";
182 } else if (state_
== kWaitingToSendBackgroundColorsAndImages
) {
183 script_argument
.SetBoolean("backgroundColorsAndImages",
184 settings_
->background_colors_and_images
);
185 state_
= kWaitingToSendMargins
;
186 failed_setting_
= "Background Colors and Images";
187 } else if (state_
== kWaitingToSendMargins
) {
188 script_argument
.SetInteger("margins", settings_
->margins
);
189 state_
= kWaitingForFinalMessage
;
190 failed_setting_
= "Margins";
191 } else if (state_
== kWaitingForFinalMessage
) {
192 // Called by |GetUI()->handler_|, it is a callback function that call
193 // |EndLoop| when an attempt to save the PDF has been made.
194 base::Closure end_loop_closure
=
195 base::Bind(&PrintPreviewObserver::EndLoop
, base::Unretained(this));
196 GetUI()->SetPdfSavedClosureForTesting(end_loop_closure
);
197 ASSERT_FALSE(pdf_file_save_path_
.empty());
198 GetUI()->SetSelectedFileForTesting(pdf_file_save_path_
);
202 ASSERT_FALSE(script_argument
.empty());
203 GetUI()->web_ui()->CallJavascriptFunction(
204 "onManipulateSettingsForTest", script_argument
);
207 // Saves the print preview settings to be sent to the print preview dialog.
208 void SetPrintPreviewSettings(const PrintPreviewSettings
& settings
) {
209 settings_
.reset(new PrintPreviewSettings(settings
));
212 // Returns the setting that could not be set in the preview dialog.
213 const std::string
& GetFailedSetting() const {
214 return failed_setting_
;
218 // Listens for messages from the print preview dialog. Specifically, it
219 // listens for 'UILoadedForTest' and 'UIFailedLoadingForTest.'
220 class UIDoneLoadingMessageHandler
: public content::WebUIMessageHandler
{
222 explicit UIDoneLoadingMessageHandler(PrintPreviewObserver
* observer
)
223 : observer_(observer
) {}
225 ~UIDoneLoadingMessageHandler() override
{}
227 // When a setting has been set succesfully, this is called and the observer
228 // is told to send the next setting to be set.
229 void HandleDone(const base::ListValue
* /* args */) {
230 observer_
->ManipulatePreviewSettings();
233 // Ends the test because a setting was not set successfully. Called when
234 // this class hears 'UIFailedLoadingForTest.'
235 void HandleFailure(const base::ListValue
* /* args */) {
236 FAIL() << "Failed to set: " << observer_
->GetFailedSetting();
239 // Allows this class to listen for the 'UILoadedForTest' and
240 // 'UIFailedLoadingForTest' messages. These messages are sent by the print
241 // preview dialog. 'UILoadedForTest' is sent when a setting has been
242 // successfully set and its effects have been finalized.
243 // 'UIFailedLoadingForTest' is sent when the setting could not be set. This
244 // causes the browser test to fail.
245 void RegisterMessages() override
{
246 web_ui()->RegisterMessageCallback(
248 base::Bind(&UIDoneLoadingMessageHandler::HandleDone
,
249 base::Unretained(this)));
251 web_ui()->RegisterMessageCallback(
252 "UIFailedLoadingForTest",
253 base::Bind(&UIDoneLoadingMessageHandler::HandleFailure
,
254 base::Unretained(this)));
258 PrintPreviewObserver
* const observer_
;
260 DISALLOW_COPY_AND_ASSIGN(UIDoneLoadingMessageHandler
);
263 // Called when the observer gets the IPC message stating that the page count
265 void OnDidGetPreviewPageCount(
266 const PrintHostMsg_DidGetPreviewPageCount_Params
¶ms
) {
267 WebContents
* web_contents
= GetDialog();
268 ASSERT_TRUE(web_contents
);
269 Observe(web_contents
);
271 PrintPreviewUI
* ui
= GetUI();
273 ASSERT_TRUE(ui
->web_ui());
275 // The |ui->web_ui()| owns the message handler.
276 ui
->web_ui()->AddMessageHandler(new UIDoneLoadingMessageHandler(this));
277 ui
->web_ui()->CallJavascriptFunction("onEnableManipulateSettingsForTest");
280 void DidCloneToNewWebContents(WebContents
* old_web_contents
,
281 WebContents
* new_web_contents
) override
{
282 Observe(new_web_contents
);
286 base::Closure quit_closure_
;
287 scoped_ptr
<PrintPreviewSettings
> settings_
;
289 // State of the observer. The state indicates what message to send
290 // next. The state advances whenever the message handler calls
291 // ManipulatePreviewSettings() on the observer.
293 std::string failed_setting_
;
294 const base::FilePath pdf_file_save_path_
;
296 DISALLOW_COPY_AND_ASSIGN(PrintPreviewObserver
);
299 class PrintPreviewPdfGeneratedBrowserTest
: public InProcessBrowserTest
{
301 PrintPreviewPdfGeneratedBrowserTest() {}
302 ~PrintPreviewPdfGeneratedBrowserTest() override
{}
304 // Navigates to the given web page, then initiates print preview and waits
305 // for all the settings to be set, then save the preview to PDF.
306 void NavigateAndPrint(const base::FilePath::StringType
& file_name
,
307 const PrintPreviewSettings
& settings
) {
308 print_preview_observer_
->SetPrintPreviewSettings(settings
);
309 base::FilePath
path(file_name
);
310 GURL gurl
= net::FilePathToFileURL(path
);
312 ui_test_utils::NavigateToURL(browser(), gurl
);
315 print_preview_observer_
->set_quit_closure(loop
.QuitClosure());
316 chrome::Print(browser());
319 // Need to check whether the save was successful. Ending the loop only
320 // means the save was attempted.
322 pdf_file_save_path_
, base::File::FLAG_OPEN
| base::File::FLAG_READ
);
323 ASSERT_TRUE(pdf_file
.IsValid());
326 // Converts the PDF to a PNG file so that the layout test can do an image
327 // diff on this image and a reference image.
330 double max_width_in_points
= 0;
331 std::vector
<uint8_t> bitmap_data
;
332 double total_height_in_pixels
= 0;
333 std::string pdf_data
;
335 ASSERT_TRUE(base::ReadFileToString(pdf_file_save_path_
, &pdf_data
));
336 ASSERT_TRUE(chrome_pdf::GetPDFDocInfo(pdf_data
.data(),
339 &max_width_in_points
));
341 ASSERT_GT(num_pages
, 0);
342 double max_width_in_pixels
=
343 ConvertUnitDouble(max_width_in_points
, kPointsPerInch
, kDpi
);
345 for (int i
= 0; i
< num_pages
; ++i
) {
346 double width_in_points
, height_in_points
;
347 ASSERT_TRUE(chrome_pdf::GetPDFPageSizeByIndex(pdf_data
.data(),
353 double width_in_pixels
= ConvertUnitDouble(
354 width_in_points
, kPointsPerInch
, kDpi
);
355 double height_in_pixels
= ConvertUnitDouble(
356 height_in_points
, kPointsPerInch
, kDpi
);
358 // The image will be rotated if |width_in_pixels| is greater than
359 // |height_in_pixels|. This is because the page will be rotated to fit
360 // within a piece of paper. Therefore, |width_in_pixels| and
361 // |height_in_pixels| have to be swapped or else they won't reflect the
362 // dimensions of the rotated page.
363 if (width_in_pixels
> height_in_pixels
)
364 std::swap(width_in_pixels
, height_in_pixels
);
366 total_height_in_pixels
+= height_in_pixels
;
367 gfx::Rect
rect(width_in_pixels
, height_in_pixels
);
368 PdfRenderSettings
settings(rect
, kDpi
, true);
370 int int_max
= std::numeric_limits
<int>::max();
371 if (settings
.area().width() > int_max
/ kColorChannels
||
372 settings
.area().height() > int_max
/ (kColorChannels
*
373 settings
.area().width())) {
374 FAIL() << "The dimensions of the image are too large."
375 << "Decrease the DPI or the dimensions of the image.";
378 std::vector
<uint8_t> page_bitmap_data(
379 kColorChannels
* settings
.area().size().GetArea());
381 ASSERT_TRUE(chrome_pdf::RenderPDFPageToBitmap(
385 page_bitmap_data
.data(),
386 settings
.area().size().width(),
387 settings
.area().size().height(),
390 FillPng(&page_bitmap_data
,
393 settings
.area().size().height());
394 bitmap_data
.insert(bitmap_data
.end(),
395 page_bitmap_data
.begin(),
396 page_bitmap_data
.end());
399 CreatePng(bitmap_data
, max_width_in_pixels
, total_height_in_pixels
);
402 // Fills out a bitmap with whitespace so that the image will correctly fit
403 // within a PNG that is wider than the bitmap itself.
404 void FillPng(std::vector
<uint8_t>* bitmap
,
409 ASSERT_GT(height
, 0);
410 ASSERT_LE(current_width
, desired_width
);
412 if (current_width
== desired_width
)
415 int current_width_in_bytes
= current_width
* kColorChannels
;
416 int desired_width_in_bytes
= desired_width
* kColorChannels
;
418 // The color format is BGRA, so to set the color to white, every pixel is
419 // set to 0xFFFFFFFF.
420 const uint8_t kColorByte
= 255;
421 std::vector
<uint8_t> filled_bitmap(
422 desired_width
* kColorChannels
* height
, kColorByte
);
423 std::vector
<uint8_t>::iterator filled_bitmap_it
= filled_bitmap
.begin();
424 std::vector
<uint8_t>::iterator bitmap_it
= bitmap
->begin();
426 for (int i
= 0; i
< height
; ++i
) {
428 bitmap_it
, bitmap_it
+ current_width_in_bytes
, filled_bitmap_it
);
429 std::advance(bitmap_it
, current_width_in_bytes
);
430 std::advance(filled_bitmap_it
, desired_width_in_bytes
);
433 bitmap
->assign(filled_bitmap
.begin(), filled_bitmap
.end());
436 // Sends the PNG image to the layout test framework for comparison.
438 // Send image header and |hash_| to the layout test framework.
439 std::cout
<< "Content-Type: image/png\n";
440 std::cout
<< "ActualHash: " << base::MD5DigestToBase16(hash_
) << "\n";
441 std::cout
<< "Content-Length: " << png_output_
.size() << "\n";
443 std::copy(png_output_
.begin(),
445 std::ostream_iterator
<unsigned char>(std::cout
, ""));
447 std::cout
<< "#EOF\n";
449 std::cerr
<< "#EOF\n";
453 // Duplicates the tab that was created when the browser opened. This is done
454 // so that the observer can listen to the duplicated tab as soon as possible
455 // and start listening for messages related to print preview.
456 void DuplicateTab() {
458 browser()->tab_strip_model()->GetActiveWebContents();
461 print_preview_observer_
.reset(
462 new PrintPreviewObserver(browser(), tab
, pdf_file_save_path_
));
463 chrome::DuplicateTab(browser());
465 WebContents
* initiator
=
466 browser()->tab_strip_model()->GetActiveWebContents();
467 ASSERT_TRUE(initiator
);
468 ASSERT_NE(tab
, initiator
);
471 // Resets the test so that another web page can be printed. It also deletes
472 // the duplicated tab as it isn't needed anymore.
475 ASSERT_EQ(2, browser()->tab_strip_model()->count());
476 chrome::CloseTab(browser());
477 ASSERT_EQ(1, browser()->tab_strip_model()->count());
480 // Creates a temporary directory to store a text file that will be used for
481 // stdin to accept input from the layout test framework. A path for the PDF
482 // file is also created. The directory and files within it are automatically
483 // cleaned up once the test ends.
484 void SetupStdinAndSavePath() {
485 // Sets the filemode to binary because it will force |std::cout| to send LF
486 // rather than CRLF. Sending CRLF will cause an error message for the
489 _setmode(_fileno(stdout
), _O_BINARY
);
490 _setmode(_fileno(stderr
), _O_BINARY
);
492 // Sends a message to the layout test framework indicating indicating
493 // that the browser test has completed setting itself up. The layout
494 // test will then expect the file path for stdin.
495 base::FilePath stdin_path
;
496 std::cout
<< "#READY\n";
499 ASSERT_TRUE(tmp_dir_
.CreateUniqueTempDir());
500 ASSERT_TRUE(base::CreateTemporaryFileInDir(tmp_dir_
.path(), &stdin_path
));
502 // Redirects |std::cin| to the file |stdin_path|. |in| is not freed because
503 // if it goes out of scope, |std::cin.rdbuf| will be freed, causing an
505 std::ifstream
* in
= new std::ifstream(stdin_path
.value().c_str());
506 ASSERT_TRUE(in
->is_open());
507 std::cin
.rdbuf(in
->rdbuf());
509 pdf_file_save_path_
=
510 tmp_dir_
.path().Append(FILE_PATH_LITERAL("dummy.pdf"));
512 // Send the file path to the layout test framework so that it can
513 // communicate with this browser test.
514 std::cout
<< "StdinPath: " << stdin_path
.value() << "\n";
515 std::cout
<< "#EOF\n";
520 // Generates a png from bitmap data and stores it in |png_output_|.
521 void CreatePng(const std::vector
<uint8_t>& bitmap_data
,
524 base::MD5Sum(static_cast<const void*>(bitmap_data
.data()),
527 gfx::Rect
png_rect(width
, height
);
529 // tEXtchecksum looks funny, but that's what the layout test framework
531 std::string
comment_title("tEXtchecksum\x00");
532 gfx::PNGCodec::Comment
hash_comment(comment_title
,
533 base::MD5DigestToBase16(hash_
));
534 std::vector
<gfx::PNGCodec::Comment
> comments
;
535 comments
.push_back(hash_comment
);
536 ASSERT_TRUE(gfx::PNGCodec::Encode(bitmap_data
.data(),
537 gfx::PNGCodec::FORMAT_BGRA
,
539 png_rect
.size().width() * kColorChannels
,
545 scoped_ptr
<PrintPreviewObserver
> print_preview_observer_
;
546 base::FilePath pdf_file_save_path_
;
548 // Vector for storing the PNG to be sent to the layout test framework.
549 // TODO(ivandavid): Eventually change this to uint32_t and make everything
550 // work with that. It might be a bit tricky to fix everything to work with
551 // uint32_t, but not too tricky.
552 std::vector
<unsigned char> png_output_
;
554 // Image hash of the bitmap that is turned into a PNG. The hash is put into
555 // the PNG as a comment, as it is needed by the layout test framework.
556 base::MD5Digest hash_
;
558 // Temporary directory for storing the pdf and the file for stdin. It is
559 // deleted by the layout tests.
560 // TODO(ivandavid): Keep it as a ScopedTempDir and change the layout test
561 // framework so that it tells the browser test how many test files there are.
562 base::ScopedTempDir tmp_dir_
;
564 DISALLOW_COPY_AND_ASSIGN(PrintPreviewPdfGeneratedBrowserTest
);
567 // This test acts as a driver for the layout test framework.
568 IN_PROC_BROWSER_TEST_F(PrintPreviewPdfGeneratedBrowserTest
,
569 MANUAL_LayoutTestDriver
) {
570 // What this code is supposed to do:
571 // - Setup communication with the layout test framework
572 // - Print webpage to a pdf
573 // - Convert pdf to a png
574 // - Send png to layout test framework, where it doesn an image diff
575 // on the image sent by this test and a reference image.
577 // Throughout this code, there will be |std::cout| statements. The layout test
578 // framework uses stdout to get data from the browser test and uses stdin
579 // to send data to the browser test. Writing "EOF\n" to |std::cout| indicates
580 // that whatever block of data that the test was expecting has been completely
581 // sent. Sometimes EOF is printed to stderr because the test will expect it
582 // from stderr in addition to stdout for certain blocks of data.=
583 SetupStdinAndSavePath();
587 while (input
.empty()) {
588 std::getline(std::cin
, input
);
593 // If the layout test framework sends "QUIT" to this test, that means there
594 // are no more tests for this instance to run and it should quit.
598 base::FilePath::StringType file_extension
= FILE_PATH_LITERAL(".pdf");
599 base::FilePath::StringType cmd
;
600 #if defined(OS_POSIX)
602 #elif defined(OS_WIN)
603 cmd
= base::UTF8ToWide(input
);
607 PrintPreviewSettings
settings(
613 cmd
.find(file_extension
) != base::FilePath::StringType::npos
);
615 // Splits the command sent by the layout test framework. The first command
616 // is always the file path to use for the test. The rest isn't relevant,
617 // so it can be ignored. The separator for the commands is an apostrophe.
618 std::vector
<base::FilePath::StringType
> cmd_arguments
;
619 base::SplitString(cmd
, '\'', &cmd_arguments
);
621 ASSERT_GE(cmd_arguments
.size(), 1U);
622 base::FilePath::StringType
test_name(cmd_arguments
[0]);
623 NavigateAndPrint(test_name
, settings
);
626 // Message to the layout test framework indicating that it should start
627 // waiting for the image data, as there is no more text data to be read.
628 // There actually isn't any text data at all, however because the layout
629 // test framework requires it, a message has to be sent to stop it from
630 // waiting for this message and start waiting for the image data.
631 std::cout
<< "#EOF\n";
639 } // namespace printing