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

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: Can now convert a pdf to a png and save it. 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
« no previous file with comments | « no previous file | chrome/browser/resources/print_preview/native_layer.js » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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..ff364f6623ef99f11820d81ac389b5d69c580eaa
--- /dev/null
+++ b/chrome/browser/printing/print_preview_pdf_generated_browsertest.cc
@@ -0,0 +1,450 @@
+// 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/logging.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_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 "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;
+
+class PrintPreviewObserver;
Lei Zhang 2014/06/26 21:36:43 The forward declarations are no longer needed.
ivandavid 2014/06/28 03:27:26 Done.
+class UIDoneLoadingMessageHandler;
+
+// 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,
+};
+
+class PrintPreviewObserver : public WebContentsObserver {
Lei Zhang 2014/06/26 21:36:43 Please write comments to briefly describe what all
ivandavid 2014/06/28 03:27:26 Done.
+ public:
+ PrintPreviewObserver(WebContents* dialog, Browser* browser)
+ : WebContentsObserver(dialog),
+ browser_(browser),
+ is_portrait_(true),
+ headers_and_footers_(true),
+ background_colors_and_images_(false),
+ margins_(printing::DEFAULT_MARGINS) {}
+
+ 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_);
+ }
+
+ 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;
Lei Zhang 2014/06/26 21:36:43 Add a comment to explain why you return false.
ivandavid 2014/06/28 03:27:26 Done.
+ }
+
+ // 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) {
+ 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", is_portrait_);
+ } else if (state == kWaitingToSendPageNumbers) {
+ script_argument_->SetString("pageRange", page_numbers_);
+ } else if (state == kWaitingToSendHeadersAndFooters) {
+ script_argument_->SetBoolean("headersAndFooters", headers_and_footers_);
+ } else if (state == kWaitingToSendBackgroundColorsAndImages) {
+ script_argument_->SetBoolean("backgroundColorsAndImages",
+ background_colors_and_images_);
+ } else if (state == kWaitingToSendMargins) {
+ script_argument_->SetInteger("margins", margins_);
+ }
+
+ args.push_back(script_argument_.get());
+ DCHECK(!script_argument_->empty());
+ DCHECK(!args.empty());
+ GetUI()->web_ui()->CallJavascriptFunction(
+ "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(bool is_portrait,
+ const 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;
+ }
+
+ private:
+ // Called when the observer gets the IPC message stating that the
+ // page count is ready.
+ 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 {
+ EndLoop();
+ }
+
+ Browser* browser_;
+ base::Closure closure_;
+
+ scoped_ptr<base::DictionaryValue> script_argument_;
Lei Zhang 2014/06/26 21:36:44 This is only used in 1 method. Make it a local var
ivandavid 2014/06/28 03:27:26 Done.
+ bool is_portrait_;
+ std::string page_numbers_;
+ bool headers_and_footers_;
+ bool background_colors_and_images_;
+ printing::MarginType margins_;
+
+ DISALLOW_COPY_AND_ASSIGN(PrintPreviewObserver);
+};
+
+class UIDoneLoadingMessageHandler : public content::WebUIMessageHandler {
+ public:
+ explicit UIDoneLoadingMessageHandler(PrintPreviewObserver* observer) :
+ observer_(observer), state_(kWaitingToSendSaveAsPdf) {}
+
+ virtual ~UIDoneLoadingMessageHandler() {
+ observer_ = NULL;
Lei Zhang 2014/06/26 21:36:43 Why do we need to do this?
ivandavid 2014/06/28 03:27:26 Don't know. It wasn't needed to I just removed it.
+ }
+
+ void HandleDone(const base::ListValue* /* args */) {
Lei Zhang 2014/06/26 21:36:44 Unless it's completely obvious, document methods,
ivandavid 2014/06/28 03:27:27 Done.
+ if (state_ == kWaitingForFinalMessage) {
+ observer_->EndLoop();
+ } else {
+ observer_->ManipulatePreviewSettings(state_);
+ state_ = static_cast<State>(static_cast<int>(state_) + 1);
+ }
+ }
+
+ void HandleFailure(const base::ListValue* /* args */) {
+ FAIL();
Lei Zhang 2014/06/26 21:36:43 You should at least print out what state the class
ivandavid 2014/06/28 03:27:26 I'll do this after I do some more javascript debug
+ }
+
+ 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);
+};
+
+void PrintPreviewObserver::OnDidGetPreviewPageCount(
Lei Zhang 2014/06/26 21:36:43 So I missed the whole inline your method impls dis
ivandavid 2014/06/28 03:27:26 This needs to be separated due to a forward declar
+ 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() {}
+
+ // TODO (ivandavid): Provide arguments for SetPrintPreviewSettings here.
Lei Zhang 2014/06/26 21:36:44 I think you should just fix the TODO. It might be
ivandavid 2014/06/28 03:27:27 Done.
+ void NavigateAndPreview(const base::FilePath::StringType& file_name) {
+ print_preview_observer_->SetPrintPreviewSettings(false,
+ "",
+ false,
+ false,
+ printing::DEFAULT_MARGINS);
+ base::FilePath directory(FILE_PATH_LITERAL("printing"));
+ base::FilePath file(file_name);
+ ui_test_utils::NavigateToURL(browser(),
+ ui_test_utils::GetTestUrl(directory, file));
+
+ base::RunLoop loop;
+ print_preview_observer_->set_quit_closure(loop.QuitClosure());
+ chrome::Print(browser());
+ loop.Run();
+ }
+
+ void Print() {
+ ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &pdf_file_save_path_));
+ pdf_file_save_path_ = pdf_file_save_path_.AppendASCII("printing");
Lei Zhang 2014/06/26 21:36:44 You should create a temporary file and delete it a
ivandavid 2014/06/28 03:27:26 I changed how this works. I create a scoped tempor
ivandavid 2014/06/28 03:27:27 Done.
+ pdf_file_save_path_ = pdf_file_save_path_.AppendASCII("dummy.pdf");
+
+ 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();
+ }
+
+ 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));
+ ASSERT_TRUE(pdf_lib.is_valid());
+ pdf_to_bitmap_func_ =
+ reinterpret_cast<PDFPageToBitmap>(
+ pdf_lib.GetFunctionPointer("RenderPDFPageToBitmap"));
+
+ ASSERT_TRUE(pdf_to_bitmap_func_);
+
+ base::File pdf_file(pdf_file_save_path_, base::File::FLAG_OPEN);
+ base::File::Info info;
+ ASSERT_TRUE(pdf_file.GetInfo(&info));
+ ASSERT_TRUE(info.size > 0);
+
+ std::string data(info.size, 0);
+ int data_size = pdf_file.Read(0, &data[0], data.size());
Lei Zhang 2014/06/26 21:36:43 Just use ReadFileToString(). It's a lot easier.
ivandavid 2014/06/28 03:27:27 Done.
+ ASSERT_TRUE(data_size == static_cast<int>(data.size()));
+ // TODO(ivandavid): Don't hardcode settings, maybe get them from
+ // print preview?
+ gfx::Rect rect(400, 400);
Lei Zhang 2014/06/26 21:36:43 You should fix this...
ivandavid 2014/06/28 03:27:27 It turns out the functionality I need isn't expose
+ printing::PdfRenderSettings settings(rect, 400, true);
+ scoped_ptr<uint8_t> bitmap_data(
+ new uint8_t[4 * settings.area().size().GetArea()]);
Lei Zhang 2014/06/26 21:36:43 You should check for integer overflow here.
ivandavid 2014/06/28 03:27:27 I will fix this when I figure out the solution to
+ // Just print a single page for now.
+ 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<unsigned char> output;
+ std::vector<gfx::PNGCodec::Comment> comments;
Lei Zhang 2014/06/26 21:36:43 You can name it empty_comments so it's obvious thi
ivandavid 2014/06/28 03:27:26 I actually need it to store an MD5 has in the png.
+ 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));
+
+ // This part is optional and only useful for debugging purposes.
+ // Do not use when doing layout tests, as the png will actually be streamed
+ // to the layout tests, and it will handle the saving of the data there.
+ base::FilePath png_path;
+ ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &png_path));
+ png_path = png_path.AppendASCII("printing");
+ png_path = png_path.AppendASCII("dummy.png");
+ int bytes_written = base::WriteFile(
+ png_path,
+ reinterpret_cast<char*>(&*output.begin()),
+ base::checked_cast<int>(output.size()));
+ ASSERT_TRUE(bytes_written == static_cast<int>(output.size()));
+ }
+
+ private:
+ virtual void SetUpOnMainThread() OVERRIDE {
+ 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);
+ }
+
+ virtual void CleanUpOnMainThread() OVERRIDE {
+ print_preview_observer_.reset();
+ }
+
+ 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);
+
+ PDFPageToBitmap pdf_to_bitmap_func_;
+
+ 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);
+
+ // TODO(ivandavid): Make this work on Windows also. Windows doesn't have
+ // the same directory structure.
+ // TODO(ivandavid): Make a temporary dir instead and place the pdf &
+ // the pipe in there.
+ base::FilePath tmp_dir("/tmp");
Lei Zhang 2014/06/26 21:36:44 There exists cross-platform code to get the temp d
ivandavid 2014/06/28 03:27:26 Done.
+ base::FilePath tmp_path;
+ ASSERT_TRUE(base::CreateTemporaryFileInDir(tmp_dir, &tmp_path));
+
+ ASSERT_TRUE(freopen(tmp_path.value().c_str(), "r", stdin));
+
+ // Sends file path to layout test framework for communication.
+ printf("StdinPath: %s\n#EOF\n", tmp_path.value().c_str());
+ fflush(stdout);
+
+ // Might have to rewrite this one. It might not work in every case.
+ // Works for now though.
+ std::string cmd;
+ std::getline(std::cin, cmd);
+ if (cmd.size() == 0) {
+ while (std::cin.eof()) {
+ std::cin.clear();
+ std::getline(std::cin, cmd);
+ if (!cmd.empty()) {
+ break;
+ }
+ }
+ }
+
+ LOG(ERROR) << cmd;
+
+ // TODO(ivandavid): Read from cmd the name of the test html file.
Lei Zhang 2014/06/26 21:36:44 So you need to make up your mind about whether the
ivandavid 2014/06/28 03:27:26 The test can now accept multiple html files and pr
ivandavid 2014/06/28 03:27:26 Done.
+ // Could be multiple test files?
+ base::FilePath::StringType test_name("test2.html");
+ NavigateAndPreview(test_name);
+ Print();
+ PdfToPng();
+
+ // Tells the layout tests that everything is done.
+ // In the future, before this part, PNG data will be sent from this program
+ // to the layout tests through stdout.
+ printf("#EOF\n");
+ fflush(stdout);
+
+ // Send image data before this EOF.
+ printf("#EOF\n");
+ fflush(stdout);
+ fprintf(stderr, "#EOF\n");
+ fclose(stdin);
+ base::DeleteFile(tmp_path, false);
+ LOG(ERROR) << "FINISHED THE TEST";
+}
« no previous file with comments | « no previous file | chrome/browser/resources/print_preview/native_layer.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698