Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(5909)

Unified Diff: chrome/browser/printing/print_preview_pdf_generated_browsertest.cc

Issue 335583004: Added a test that currently is able to print to pdf. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Refactored the browsertest. Fixed javascript bug where clicked was being used rather than checked. Created 6 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
diff --git a/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc b/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
new file mode 100644
index 0000000000000000000000000000000000000000..7426f13fa731f34e323976fd242d140928d51033
--- /dev/null
+++ b/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
@@ -0,0 +1,536 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include <cstdio>
+#include <iostream>
+#include <limits>
+#include <string>
+#include <vector>
+
+#include "base/file_util.h"
+#include "base/files/file.h"
+#include "base/files/file_path.h"
+#include "base/files/scoped_temp_dir.h"
+#include "base/logging.h"
+#include "base/md5.h"
+#include "base/memory/scoped_ptr.h"
+#include "base/numerics/safe_conversions.h"
+#include "base/path_service.h"
+#include "base/run_loop.h"
+#include "base/scoped_native_library.h"
+#include "base/strings/string_split.h"
+#include "base/strings/string_util.h"
+#include "chrome/app/chrome_command_ids.h"
+#include "chrome/browser/net/referrer.h"
+#include "chrome/browser/printing/print_preview_dialog_controller.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser.h"
+#include "chrome/browser/ui/browser_commands.h"
+#include "chrome/browser/ui/tabs/tab_strip_model.h"
+#include "chrome/browser/ui/webui/print_preview/print_preview_handler.h"
+#include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
+#include "chrome/browser/ui/webui/print_preview/sticky_settings.h"
+#include "chrome/common/chrome_paths.h"
+#include "chrome/common/print_messages.h"
+#include "chrome/common/url_constants.h"
+#include "chrome/test/base/in_process_browser_test.h"
+#include "chrome/test/base/ui_test_utils.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_ui_message_handler.h"
+#include "content/public/common/page_transition_types.h"
+#include "content/public/test/browser_test_utils.h"
+#include "content/public/test/test_navigation_observer.h"
+#include "content/public/test/test_utils.h"
+#include "net/base/filename_util.h"
+#include "printing/pdf_render_settings.h"
+#include "printing/print_job_constants.h"
+#include "ui/events/keycodes/keyboard_codes.h"
+#include "ui/gfx/codec/png_codec.h"
+#include "ui/gfx/geometry/rect.h"
+#include "url/gurl.h"
+#include "ipc/ipc_message_macros.h"
+
+using content::WebContents;
+using content::WebContentsObserver;
+
+// Message refers to the 'UILoaded' message from print_preview.js.
+// It gets sent either from onPreviewGenerationDone or from
+// onManipulateSettings_() in print_preview.js
+enum State {
+ // Waiting for the first message so the program can select Save as PDF
+ kWaitingToSendSaveAsPdf = 0,
+ // Waiting for the second message so the test can set the layout
+ kWaitingToSendLayoutSettings = 1,
+ // Waiting for the third message so the test can set the page numbers
+ kWaitingToSendPageNumbers = 2,
+ // Waiting for the forth message so the test can set the headers checkbox
+ kWaitingToSendHeadersAndFooters = 3,
+ // Waiting for the fifth message so the test can set the background checkbox
+ kWaitingToSendBackgroundColorsAndImages = 4,
+ // Waiting for the sixth message so the test can set the margins combobox
+ kWaitingToSendMargins = 5,
+ // Waiting for the final message so the program can save to PDF.
+ kWaitingForFinalMessage = 6,
+};
+
+struct PrintPreviewSettings {
+ PrintPreviewSettings() {}
Lei Zhang 2014/06/30 22:38:32 Do you need a default ctor? ... where the members
ivandavid 2014/07/03 03:12:02 At the time I did, however I rewrote the code so t
ivandavid 2014/07/03 03:12:02 Done.
+
+ PrintPreviewSettings(bool is_portrait,
+ std::string page_numbers,
+ bool headers_and_footers,
+ bool background_colors_and_images,
+ printing::MarginType margins)
+ : is_portrait_(is_portrait),
+ page_numbers_(page_numbers),
+ headers_and_footers_(headers_and_footers),
+ background_colors_and_images_(background_colors_and_images),
+ margins_(margins) {}
+
+ bool is_portrait_;
Lei Zhang 2014/06/30 22:38:32 struct members don't have the trailing underscore
ivandavid 2014/07/03 03:12:03 Done.
+ std::string page_numbers_;
+ bool headers_and_footers_;
+ bool background_colors_and_images_;
+ printing::MarginType margins_;
+};
+
+// Observes the print preview webpage. Once it observes the
+// PreviewPageCount message, will send a sequence of commands
+// to the print preview dialog and change the settings of the
+// preview dialog.
+class PrintPreviewObserver : public WebContentsObserver {
+ public:
+ PrintPreviewObserver(WebContents* dialog, Browser* browser)
+ : WebContentsObserver(dialog),
+ browser_(browser) {}
+
+ virtual ~PrintPreviewObserver() {}
+
+ // Sets closure for the observer so that it can end the loop.
+ void set_quit_closure(const base::Closure &closure) {
+ closure_ = closure;
+ }
+
+ // Actually stops the message_loop so that the test can proceed.
+ void EndLoop() {
+ base::MessageLoop::current()->PostTask(FROM_HERE, closure_);
+ }
+
+ // This method must always return false. If it ever returns true,
+ // it will cause the test to hang. This is because the
+ // PrintPreviewMessageHandler should still handle all of the messages to
+ // progress the print preview process.
+ bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
+ IPC_BEGIN_MESSAGE_MAP(PrintPreviewObserver, message)
+ IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPreviewPageCount,
+ OnDidGetPreviewPageCount)
+ IPC_MESSAGE_UNHANDLED(break;)
+ IPC_END_MESSAGE_MAP();
+ return false;
+ }
+
+ // Gets the web contents for the print preview dialog so that
+ // the UI and other elements can be accessed.
+ WebContents* GetDialog() {
+ WebContents* tab = browser_->tab_strip_model()->GetActiveWebContents();
+ printing::PrintPreviewDialogController* dialog_controller =
+ printing::PrintPreviewDialogController::GetInstance();
+ WebContents* web_contents =
+ dialog_controller->GetPrintPreviewForContents(tab);
+ return web_contents;
+ }
+
+ // Gets the PrintPreviewUI so that certain elements can be accessed.
+ PrintPreviewUI* GetUI() {
+ return static_cast<PrintPreviewUI*>(
+ GetDialog()->GetWebUI()->GetController());
+ }
+
+ // Calls a javascript function that will change the print preview settings,
+ // such as the layout, the margins, page numbers, etc.
+ void ManipulatePreviewSettings(State state) {
+ scoped_ptr<base::DictionaryValue> script_argument(
+ new base::DictionaryValue());
+ std::vector<const base::Value*> args;
+ script_argument.reset(new base::DictionaryValue());
+ if (state == kWaitingToSendSaveAsPdf) {
+ script_argument->SetBoolean("selectSaveAsPdfDestination", true);
+ } else if (state == kWaitingToSendLayoutSettings) {
+ script_argument->SetBoolean("layoutSettings.portrait",
+ settings_.is_portrait_);
+ } else if (state == kWaitingToSendPageNumbers) {
+ script_argument->SetString("pageRange", settings_.page_numbers_);
+ } else if (state == kWaitingToSendHeadersAndFooters) {
+ script_argument->SetBoolean("headersAndFooters",
+ settings_.headers_and_footers_);
+ } else if (state == kWaitingToSendBackgroundColorsAndImages) {
+ script_argument->SetBoolean("backgroundColorsAndImages",
+ settings_.background_colors_and_images_);
+ } else if (state == kWaitingToSendMargins) {
+ script_argument->SetInteger("margins", settings_.margins_);
+ }
+
+ args.push_back(script_argument.get());
+ DCHECK(!script_argument->empty());
+ DCHECK(!args.empty());
+ GetUI()->web_ui()->CallJavascriptFunction(
Lei Zhang 2014/06/30 22:38:31 Since the size of |args| is only ever 1, you can d
ivandavid 2014/07/03 03:12:02 Done.
+ "onManipulateSettingsForTest", args);
+ }
+
+ // Function to set the print preview settings and save them so they
+ // can be sent later. Currently only used in the constructor. Will be
+ // used when creating a test and take command line arguments.
+ // |page_numbers| is a comma separated page range.
+ // Example: "1-5,9" will print pages 1 through 5 and page 9.
+ // The pages specified must be less than or equal to the maximum
+ // page number. An empty string seems to be valid input, however
+ // further testing will be required to see if that is actually
+ // true.
+ void SetPrintPreviewSettings(PrintPreviewSettings settings) {
Lei Zhang 2014/06/30 22:38:31 pass by const ref
ivandavid 2014/07/03 03:12:02 Done.
+ settings_ = settings;
+ }
+
+ private:
+ // Called when the observer gets the IPC message stating that the
+ // page count is ready.
+ // Due to forward declaration problem, the definition of the function
+ // must be separated from the declaration.
+ void OnDidGetPreviewPageCount(
+ const PrintHostMsg_DidGetPreviewPageCount_Params &params);
+
+ void DidCloneToNewWebContents(WebContents* old_web_contents,
+ WebContents* new_web_contents)
+ OVERRIDE {
+ Observe(new_web_contents);
+ }
+
+ void WebContentsDestroyed() OVERRIDE {
+ LOG(ERROR) << "DESTROYED";
Lei Zhang 2014/06/30 22:38:32 Accidentally included?
ivandavid 2014/07/03 03:12:02 Yeah. Done.
+ EndLoop();
+ }
+
+ Browser* browser_;
+ base::Closure closure_;
+ PrintPreviewSettings settings_;
+
+ DISALLOW_COPY_AND_ASSIGN(PrintPreviewObserver);
+};
+
+// Listens for messages from the print preview ui. Its a different
+// set of messages, which is why two different classes are needed for this.
+// When it gets the "UILoadedForTest" message, it prompts the observer to
+// send a new message. When it gets the "UIFailedLoadingForTest" it just
+// calls FAIL() and the test stops.
+class UIDoneLoadingMessageHandler : public content::WebUIMessageHandler {
+ public:
+ explicit UIDoneLoadingMessageHandler(PrintPreviewObserver* observer) :
+ observer_(observer), state_(kWaitingToSendSaveAsPdf) {}
+
+ virtual ~UIDoneLoadingMessageHandler() {}
+
+ // When a setting has been set succesfully, this is called. If there
+ // are more settings to be set, ManipulatePreviewSettings on the observer
+ // is called to set the next settings. If there aren't anymore settings
+ // to be set, the loop that the observer is waiting in is ended.
+ void HandleDone(const base::ListValue* /* args */) {
+ if (state_ == kWaitingForFinalMessage) {
+ observer_->EndLoop();
+ } else {
+ observer_->ManipulatePreviewSettings(state_);
+ state_ = static_cast<State>(static_cast<int>(state_) + 1);
+ }
+ }
+
+ // Ends the test because a setting was not set successfully,
+ // therefore, the test shouldn't continue.
+ void HandleFailure(const base::ListValue* /* args */) {
+ FAIL();
+ }
+
+ // Sets up this class to listen for the UILoadedForTest and
+ // UIFailedLoadingForTest messages. These messages are sent
+ // by print_preview.js. On UILoadedForTest, a settings has
+ // been successfully set and its effects on the pdf have been finalized.
+ // On UIFaieldLoadingForTest a setting has not been successfully set
+ // and the test should fail.
+ void RegisterMessages() OVERRIDE {
+ web_ui()->RegisterMessageCallback(
+ "UILoadedForTest",
+ base::Bind(&UIDoneLoadingMessageHandler::HandleDone,
+ base::Unretained(this)));
+
+ web_ui()->RegisterMessageCallback(
+ "UIFailedLoadingForTest",
+ base::Bind(&UIDoneLoadingMessageHandler::HandleFailure,
+ base::Unretained(this)));
+ }
+
+ private:
+ PrintPreviewObserver* observer_;
+ State state_;
+
+ DISALLOW_COPY_AND_ASSIGN(UIDoneLoadingMessageHandler);
+};
+
+// This function needs to be forward declared.
+void PrintPreviewObserver::OnDidGetPreviewPageCount(
+ const PrintHostMsg_DidGetPreviewPageCount_Params &params) {
+ WebContents* web_contents = GetDialog();
+ PrintPreviewUI* ui = GetUI();
+ ASSERT_TRUE(ui);
+ ASSERT_TRUE(ui->web_ui());
+ ui->web_ui()->CallJavascriptFunction("onEnableManipulateSettingsForTest");
+ Observe(web_contents);
+ ui->web_ui()->AddMessageHandler(new UIDoneLoadingMessageHandler(this));
+}
+
+class PrintPreviewPdfGeneratedBrowserTest : public InProcessBrowserTest {
+ public:
+ PrintPreviewPdfGeneratedBrowserTest() {}
+ virtual ~PrintPreviewPdfGeneratedBrowserTest() {}
+
+ // Navigates to the web page given, then initiates print preview
+ // and waits for all the settings to be set.
+ void NavigateAndPreview(const base::FilePath::StringType& file_name,
+ PrintPreviewSettings settings) {
+ print_preview_observer_->SetPrintPreviewSettings(settings);
+ base::FilePath path(file_name);
+ GURL gurl = net::FilePathToFileURL(path);
+
+ ui_test_utils::NavigateToURL(browser(),
+ gurl);
Lei Zhang 2014/06/30 22:38:31 fits on previous line
ivandavid 2014/07/03 03:12:02 Done.
+
+ base::RunLoop loop;
+ print_preview_observer_->set_quit_closure(loop.QuitClosure());
+ chrome::Print(browser());
+ loop.Run();
+ }
+
+ // Prints the webpage to pdf, after the settings have been set.
+ void Print(const base::FilePath& dir) {
+ pdf_file_save_path_ = dir.AppendASCII("dummy.pdf");
Lei Zhang 2014/06/30 22:38:32 Why not just set |pdf_file_save_path_| before you
ivandavid 2014/07/03 03:12:03 Done.
+ base::RunLoop loop;
+ print_preview_observer_->set_quit_closure(loop.QuitClosure());
+ print_preview_observer_->GetUI()->handler_->FileSelected(
+ pdf_file_save_path_, 0, NULL);
+ loop.Run();
+ }
+
+ // Converts the pdf to a a png file, so that the layout test can
Lei Zhang 2014/06/30 22:38:32 typo
ivandavid 2014/07/03 03:12:02 Done.
+ // do an image diff on this image and a reference image.
+ void PdfToPng() {
+ base::ScopedNativeLibrary pdf_lib;
+ base::FilePath pdf_module_path;
+
+ ASSERT_TRUE(PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_module_path));
+ ASSERT_TRUE(base::PathExists(pdf_module_path));
+ pdf_lib.Reset(base::LoadNativeLibrary(pdf_module_path, NULL));
+
+ LOG(ERROR) << pdf_module_path.value();
Lei Zhang 2014/06/30 22:38:31 remove
ivandavid 2014/07/03 03:12:02 Done.
+
+ ASSERT_TRUE(pdf_lib.is_valid());
+ pdf_to_bitmap_func_ =
+ reinterpret_cast<PDFPageToBitmap>(
+ pdf_lib.GetFunctionPointer("RenderPDFPageToBitmap"));
+
+ ASSERT_TRUE(pdf_to_bitmap_func_);
+
+
+ std::string data;
+ gfx::Rect rect(800, 800);
+
+ ASSERT_TRUE(base::ReadFileToString(pdf_file_save_path_, &data));
+ printing::PdfRenderSettings settings(rect, 300, true);
+
+ // Multiple by 4 b/c that's the # of color channels.
+ scoped_ptr<uint8_t> bitmap_data(
+ new uint8_t[4 * settings.area().size().GetArea()]);
+
+ // Just print a single page for now, print all in the future.
+ // The pages that are to be tested are selected when
+ // sending messages to print preview.
+ ASSERT_TRUE(pdf_to_bitmap_func_(data.data(),
+ data.size(),
+ 0,
+ bitmap_data.get(),
+ settings.area().size().width(),
+ settings.area().size().height(),
+ settings.dpi(),
+ settings.dpi(),
+ true));
+
+ std::vector<gfx::PNGCodec::Comment> comments;
+ ASSERT_TRUE(
+ gfx::PNGCodec::Encode(static_cast<unsigned char*>(
+ bitmap_data.get()),
+ gfx::PNGCodec::FORMAT_BGRA,
+ settings.area().size(),
+ settings.area().size().width() * sizeof(uint32_t),
+ false,
+ comments,
+ &output_));
+
+ std::string hash_input(output_.begin(), output_.end());
+
+ base::MD5Sum(hash_input.data(),
+ hash_input.size(),
Lei Zhang 2014/06/30 22:38:31 this all fits on 1 line?
ivandavid 2014/07/03 03:12:03 Done.
+ &hash_);
+
+ std::string comment_title("tEXtchecksum\x00");
+ gfx::PNGCodec::Comment hash_comment(
+ comment_title,
+ base::MD5DigestToBase16(hash_));
+
+ comments.push_back(hash_comment);
+
+ // Have to do it twice, b/c we need to get the hash of the png
+ // then actually write the hash into the png. Probably not
+ // the correct way to do this, but for now it'll do as long as
+ // it passes the test. Find out how content shell does it and then
+ // emulate it. The hash's don't have to be equal for the test to
+ // succeed, only the images do, however if the hashes
+ // are the same, there is no point in doing image_diff since its
+ // essentially the same file.
+ ASSERT_TRUE(
+ gfx::PNGCodec::Encode(static_cast<unsigned char*>(
+ bitmap_data.get()),
+ gfx::PNGCodec::FORMAT_BGRA,
+ settings.area().size(),
+ settings.area().size().width() * sizeof(uint32_t),
+ false,
+ comments,
+ &output_));
+ }
+
+ // Sends the png image to the layout test framework for comparison.
+ void SendPng() {
+ // Send image header & hash_
+ printf("Content-Type: image/png\n");
+ printf("ActualHash: %s\n", base::MD5DigestToBase16(hash_).data());
+ printf("Content-Length: %lu\n", output_.size());
Lei Zhang 2014/06/30 22:38:32 You probably need the PRIuS macro from base/format
ivandavid 2014/07/03 03:12:03 Done.
+ std::vector<unsigned char>::iterator it = output_.begin();
Lei Zhang 2014/06/30 22:38:32 For vectors, if you write: for (size_t i = 0; i <
ivandavid 2014/07/03 03:12:02 Done.
+ std::vector<unsigned char>::iterator end = output_.end();
+
+ for ( ; it != end; it++)
+ printf("%c", *it);
+
+ printf("#EOF\n");
+ fflush(stdout);
+ fprintf(stderr, "#EOF\n");
+ fflush(stderr);
+ }
+
+ // Duplicates the tab that was created when the browser opened.
+ // This is done, so that the observer can listen to the duplicated
+ // tab as soon as possible and start listening for messages related to
+ // print preview.
+ void DuplicateTab() {
+ WebContents* tab =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ ASSERT_TRUE(tab);
+
+ print_preview_observer_.reset(new PrintPreviewObserver(tab, browser()));
+ chrome::DuplicateTab(browser());
+
+ WebContents* initiator =
+ browser()->tab_strip_model()->GetActiveWebContents();
+ ASSERT_TRUE(initiator);
+ ASSERT_NE(tab, initiator);
+ }
+
+ // Resets the test so that another web page can be printing.
+ // Deletes the duplicate tab as it isn't needed anymore.
+ void Clean() {
+ output_.clear();
+ ASSERT_TRUE(browser()->tab_strip_model()->count() == 2);
Lei Zhang 2014/06/30 22:38:31 ASSERT_EQ
ivandavid 2014/07/03 03:12:02 Done.
+ chrome::CloseTab(browser());
+ ASSERT_TRUE(browser()->tab_strip_model()->count() == 1);
+ pdf_file_save_path_.clear();
+ }
+
+ private:
+ scoped_ptr<PrintPreviewObserver> print_preview_observer_;
+ base::FilePath pdf_file_save_path_;
+
+ typedef bool (*PDFPageToBitmap) (const void * pdf_buffer,
+ int pdf_buffer_size,
+ int page_number,
+ void* bitmap_buffer,
+ int bitmap_width,
+ int bitmap_height,
+ int dpi_x,
+ int dpi_y,
+ bool autorotate);
+
+ typedef int (*PageSizeByIndex) (const void * pdf_buffer,
+ int page_index,
+ double* width,
+ double* height);
+
+ PDFPageToBitmap pdf_to_bitmap_func_;
+ PageSizeByIndex pdf_page_size_func_;
+ std::vector<unsigned char> output_;
+ base::MD5Digest hash_;
+
+ DISALLOW_COPY_AND_ASSIGN(PrintPreviewPdfGeneratedBrowserTest);
+};
+
+IN_PROC_BROWSER_TEST_F(PrintPreviewPdfGeneratedBrowserTest,
+ DISABLED_DummyTest) {
+ // What this code is supposed to do: Setup communication with the
+ // layout test framework, print webpage to a pdf, convert that
+ // pdf to a png, then send that png file to the layout test framework,
+ // where the framework will do an image diff.
+ printf("#READY\n");
+ fflush(stdout);
+
+ base::ScopedTempDir tmp_dir;
+ base::FilePath tmp_path;
+
+ ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
+ ASSERT_TRUE(base::CreateTemporaryFileInDir(tmp_dir.path(), &tmp_path));
+ ASSERT_TRUE(freopen(tmp_path.value().c_str(), "r", stdin));
+
+ printf("StdinPath: %s\n#EOF\n", tmp_path.value().c_str());
+ fflush(stdout);
+
+ while (true) {
+ DuplicateTab();
+
+ base::FilePath::StringType cmd;
Lei Zhang 2014/06/30 22:38:31 I don't think std::getline() takes a std::wstring
ivandavid 2014/07/03 03:12:02 I think I fixed it. I defined a macro STDIN_STREAM
+ std::getline(std::cin, cmd);
+ if (cmd.size() == 0) {
Lei Zhang 2014/06/30 22:38:32 .empty()
ivandavid 2014/07/03 03:12:02 Done.
+ while (std::cin.eof()) {
+ std::cin.clear();
+ std::getline(std::cin, cmd);
+ if (!cmd.empty()) {
+ break;
+ }
+ }
+ }
+
+ // TODO(ivandavid): Have the layout test framework read a settings file,
+ // and have those settings be place in this settings struct.
+ PrintPreviewSettings settings(true,
+ "",
+ false,
+ false,
+ printing::DEFAULT_MARGINS);
+
+ std::vector<base::FilePath::StringType> cmd_arguments;
+ base::SplitString(cmd, '\'', &cmd_arguments);
+ base::FilePath::StringType test_name(cmd_arguments[0]);
+ NavigateAndPreview(test_name, settings);
+ Print(tmp_dir.path());
+ PdfToPng();
+
+ printf("#EOF\n");
+ fflush(stdout);
+
+ SendPng();
+ Clean();
+ }
+ fclose(stdin);
+ base::DeleteFile(tmp_path, false);
Lei Zhang 2014/06/30 22:38:32 You don't need this. Since |tmp_path| is within |t
ivandavid 2014/07/03 03:12:02 Done.
+}

Powered by Google App Engine
This is Rietveld 408576698