Update printing code

This commit is contained in:
Cheng Zhao 2014-12-07 06:55:40 -08:00
parent 6d32db32ef
commit d309fd5a27
23 changed files with 665 additions and 485 deletions

View file

@ -283,6 +283,7 @@
'chromium_src/chrome/browser/printing/print_job_manager.h', 'chromium_src/chrome/browser/printing/print_job_manager.h',
'chromium_src/chrome/browser/printing/print_job_worker.cc', 'chromium_src/chrome/browser/printing/print_job_worker.cc',
'chromium_src/chrome/browser/printing/print_job_worker.h', 'chromium_src/chrome/browser/printing/print_job_worker.h',
'chromium_src/chrome/browser/printing/print_job_worker_owner.cc',
'chromium_src/chrome/browser/printing/print_job_worker_owner.h', 'chromium_src/chrome/browser/printing/print_job_worker_owner.h',
'chromium_src/chrome/browser/printing/print_view_manager_base.cc', 'chromium_src/chrome/browser/printing/print_view_manager_base.cc',
'chromium_src/chrome/browser/printing/print_view_manager_base.h', 'chromium_src/chrome/browser/printing/print_view_manager_base.h',
@ -293,8 +294,6 @@
'chromium_src/chrome/browser/printing/printer_query.h', 'chromium_src/chrome/browser/printing/printer_query.h',
'chromium_src/chrome/browser/printing/printing_message_filter.cc', 'chromium_src/chrome/browser/printing/printing_message_filter.cc',
'chromium_src/chrome/browser/printing/printing_message_filter.h', 'chromium_src/chrome/browser/printing/printing_message_filter.h',
'chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.cc',
'chromium_src/chrome/browser/printing/printing_ui_web_contents_observer.h',
'chromium_src/chrome/browser/speech/tts_controller.h', 'chromium_src/chrome/browser/speech/tts_controller.h',
'chromium_src/chrome/browser/speech/tts_controller_impl.cc', 'chromium_src/chrome/browser/speech/tts_controller_impl.cc',
'chromium_src/chrome/browser/speech/tts_controller_impl.h', 'chromium_src/chrome/browser/speech/tts_controller_impl.h',

View file

@ -56,7 +56,7 @@ AtomBrowserClient::~AtomBrowserClient() {
void AtomBrowserClient::RenderProcessWillLaunch( void AtomBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host) { content::RenderProcessHost* host) {
int id = host->GetID(); int id = host->GetID();
host->AddFilter(new PrintingMessageFilter(host->GetID())); host->AddFilter(new printing::PrintingMessageFilter(host->GetID()));
host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext())); host->AddFilter(new TtsMessageFilter(id, host->GetBrowserContext()));
} }

View file

@ -161,7 +161,7 @@ void AtomRendererClient::DidCreateScriptContext(blink::WebFrame* frame,
} }
void AtomRendererClient::WillReleaseScriptContext( void AtomRendererClient::WillReleaseScriptContext(
blink::WebFrame* frame, blink::WebLocalFrame* frame,
v8::Handle<v8::Context> context, v8::Handle<v8::Context> context,
int world_id) { int world_id) {
node::Environment* env = node::Environment::GetCurrent(context); node::Environment* env = node::Environment::GetCurrent(context);

View file

@ -27,7 +27,7 @@ class AtomRendererClient : public content::ContentRendererClient,
virtual ~AtomRendererClient(); virtual ~AtomRendererClient();
// Forwarded by RenderFrameObserver. // Forwarded by RenderFrameObserver.
void WillReleaseScriptContext(blink::WebFrame* frame, void WillReleaseScriptContext(blink::WebLocalFrame* frame,
v8::Handle<v8::Context> context, v8::Handle<v8::Context> context,
int world_id); int world_id);

View file

@ -32,29 +32,25 @@ void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
namespace printing { namespace printing {
PrintJob::PrintJob() PrintJob::PrintJob()
: ui_message_loop_(base::MessageLoop::current()), : source_(NULL),
source_(NULL),
worker_(), worker_(),
settings_(), settings_(),
is_job_pending_(false), is_job_pending_(false),
is_canceling_(false), is_canceling_(false),
quit_factory_(this) { quit_factory_(this) {
DCHECK(ui_message_loop_);
// This is normally a UI message loop, but in unit tests, the message loop is // This is normally a UI message loop, but in unit tests, the message loop is
// of the 'default' type. // of the 'default' type.
DCHECK(base::MessageLoopForUI::IsCurrent() || DCHECK(base::MessageLoopForUI::IsCurrent() ||
ui_message_loop_->type() == base::MessageLoop::TYPE_DEFAULT); base::MessageLoop::current()->type() ==
ui_message_loop_->AddDestructionObserver(this); base::MessageLoop::TYPE_DEFAULT);
} }
PrintJob::~PrintJob() { PrintJob::~PrintJob() {
ui_message_loop_->RemoveDestructionObserver(this);
// The job should be finished (or at least canceled) when it is destroyed. // The job should be finished (or at least canceled) when it is destroyed.
DCHECK(!is_job_pending_); DCHECK(!is_job_pending_);
DCHECK(!is_canceling_); DCHECK(!is_canceling_);
if (worker_.get()) DCHECK(!worker_ || !worker_->IsRunning());
DCHECK(worker_->message_loop() == NULL); DCHECK(RunsTasksOnCurrentThread());
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current());
} }
void PrintJob::Initialize(PrintJobWorkerOwner* job, void PrintJob::Initialize(PrintJobWorkerOwner* job,
@ -85,7 +81,7 @@ void PrintJob::Initialize(PrintJobWorkerOwner* job,
void PrintJob::Observe(int type, void PrintJob::Observe(int type,
const content::NotificationSource& source, const content::NotificationSource& source,
const content::NotificationDetails& details) { const content::NotificationDetails& details) {
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
switch (type) { switch (type) {
case chrome::NOTIFICATION_PRINT_JOB_EVENT: { case chrome::NOTIFICATION_PRINT_JOB_EVENT: {
OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr()); OnNotifyPrintJobEvent(*content::Details<JobEventDetails>(details).ptr());
@ -107,10 +103,6 @@ PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) {
return NULL; return NULL;
} }
base::MessageLoop* PrintJob::message_loop() {
return ui_message_loop_;
}
const PrintSettings& PrintJob::settings() const { const PrintSettings& PrintJob::settings() const {
return settings_; return settings_;
} }
@ -122,23 +114,20 @@ int PrintJob::cookie() const {
return document_->cookie(); return document_->cookie();
} }
void PrintJob::WillDestroyCurrentMessageLoop() {
NOTREACHED();
}
void PrintJob::StartPrinting() { void PrintJob::StartPrinting() {
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
DCHECK(worker_->message_loop()); DCHECK(worker_->IsRunning());
DCHECK(!is_job_pending_); DCHECK(!is_job_pending_);
if (!worker_->message_loop() || is_job_pending_) if (!worker_->IsRunning() || is_job_pending_)
return; return;
// Real work is done in PrintJobWorker::StartPrinting(). // Real work is done in PrintJobWorker::StartPrinting().
worker_->message_loop()->PostTask( worker_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(&HoldRefCallback,
base::Bind(&HoldRefCallback, make_scoped_refptr(this), make_scoped_refptr(this),
base::Bind(&PrintJobWorker::StartPrinting, base::Bind(&PrintJobWorker::StartPrinting,
base::Unretained(worker_.get()), document_))); base::Unretained(worker_.get()),
document_)));
// Set the flag right now. // Set the flag right now.
is_job_pending_ = true; is_job_pending_ = true;
@ -152,7 +141,7 @@ void PrintJob::StartPrinting() {
} }
void PrintJob::Stop() { void PrintJob::Stop() {
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
if (quit_factory_.HasWeakPtrs()) { if (quit_factory_.HasWeakPtrs()) {
// In case we're running a nested message loop to wait for a job to finish, // In case we're running a nested message loop to wait for a job to finish,
@ -164,7 +153,7 @@ void PrintJob::Stop() {
// Be sure to live long enough. // Be sure to live long enough.
scoped_refptr<PrintJob> handle(this); scoped_refptr<PrintJob> handle(this);
if (worker_->message_loop()) { if (worker_->IsRunning()) {
ControlledWorkerShutdown(); ControlledWorkerShutdown();
} else { } else {
// Flush the cached document. // Flush the cached document.
@ -180,10 +169,8 @@ void PrintJob::Cancel() {
// Be sure to live long enough. // Be sure to live long enough.
scoped_refptr<PrintJob> handle(this); scoped_refptr<PrintJob> handle(this);
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
base::MessageLoop* worker_loop = if (worker_ && worker_->IsRunning()) {
worker_.get() ? worker_->message_loop() : NULL;
if (worker_loop) {
// Call this right now so it renders the context invalid. Do not use // Call this right now so it renders the context invalid. Do not use
// InvokeLater since it would take too much time. // InvokeLater since it would take too much time.
worker_->Cancel(); worker_->Cancel();
@ -237,14 +224,15 @@ void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) {
settings_ = document_->settings(); settings_ = document_->settings();
} }
if (worker_.get() && worker_->message_loop()) { if (worker_) {
DCHECK(!is_job_pending_); DCHECK(!is_job_pending_);
// Sync the document with the worker. // Sync the document with the worker.
worker_->message_loop()->PostTask( worker_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(&HoldRefCallback,
base::Bind(&HoldRefCallback, make_scoped_refptr(this), make_scoped_refptr(this),
base::Bind(&PrintJobWorker::OnDocumentChanged, base::Bind(&PrintJobWorker::OnDocumentChanged,
base::Unretained(worker_.get()), document_))); base::Unretained(worker_.get()),
document_)));
} }
} }
@ -264,7 +252,6 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
} }
case JobEventDetails::NEW_DOC: case JobEventDetails::NEW_DOC:
case JobEventDetails::NEW_PAGE: case JobEventDetails::NEW_PAGE:
case JobEventDetails::PAGE_DONE:
case JobEventDetails::JOB_DONE: case JobEventDetails::JOB_DONE:
case JobEventDetails::ALL_PAGES_REQUESTED: { case JobEventDetails::ALL_PAGES_REQUESTED: {
// Don't care. // Don't care.
@ -276,6 +263,8 @@ void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) {
FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this)); FROM_HERE, base::Bind(&PrintJob::OnDocumentDone, this));
break; break;
} }
case JobEventDetails::PAGE_DONE:
break;
default: { default: {
NOTREACHED(); NOTREACHED();
break; break;
@ -300,7 +289,7 @@ void PrintJob::OnDocumentDone() {
} }
void PrintJob::ControlledWorkerShutdown() { void PrintJob::ControlledWorkerShutdown() {
DCHECK_EQ(ui_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
// The deadlock this code works around is specific to window messaging on // The deadlock this code works around is specific to window messaging on
// Windows, so we aren't likely to need it on any other platforms. // Windows, so we aren't likely to need it on any other platforms.

View file

@ -15,15 +15,19 @@
class Thread; class Thread;
namespace base {
class RefCountedMemory;
}
namespace printing { namespace printing {
// See definition below.
class JobEventDetails; class JobEventDetails;
class MetafilePlayer;
class PdfToEmfConverter;
class PrintJobWorker;
class PrintedDocument; class PrintedDocument;
class PrintedPage; class PrintedPage;
class PrintedPagesSource; class PrintedPagesSource;
class PrintJobWorker;
class PrinterQuery; class PrinterQuery;
// Manages the print work for a specific document. Talks to the printer through // Manages the print work for a specific document. Talks to the printer through
@ -33,8 +37,7 @@ class PrinterQuery;
// reference to the job to be sure it is kept alive. All the code in this class // reference to the job to be sure it is kept alive. All the code in this class
// runs in the UI thread. // runs in the UI thread.
class PrintJob : public PrintJobWorkerOwner, class PrintJob : public PrintJobWorkerOwner,
public content::NotificationObserver, public content::NotificationObserver {
public base::MessageLoop::DestructionObserver {
public: public:
// Create a empty PrintJob. When initializing with this constructor, // Create a empty PrintJob. When initializing with this constructor,
// post-constructor initialization must be done with Initialize(). // post-constructor initialization must be done with Initialize().
@ -54,13 +57,9 @@ class PrintJob : public PrintJobWorkerOwner,
virtual void GetSettingsDone(const PrintSettings& new_settings, virtual void GetSettingsDone(const PrintSettings& new_settings,
PrintingContext::Result result) OVERRIDE; PrintingContext::Result result) OVERRIDE;
virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) OVERRIDE; virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) OVERRIDE;
virtual base::MessageLoop* message_loop() OVERRIDE;
virtual const PrintSettings& settings() const OVERRIDE; virtual const PrintSettings& settings() const OVERRIDE;
virtual int cookie() const OVERRIDE; virtual int cookie() const OVERRIDE;
// DestructionObserver implementation.
virtual void WillDestroyCurrentMessageLoop() OVERRIDE;
// Starts the actual printing. Signals the worker that it should begin to // Starts the actual printing. Signals the worker that it should begin to
// spool as soon as data is available. // spool as soon as data is available.
void StartPrinting(); void StartPrinting();
@ -116,10 +115,6 @@ class PrintJob : public PrintJobWorkerOwner,
content::NotificationRegistrar registrar_; content::NotificationRegistrar registrar_;
// Main message loop reference. Used to send notifications in the right
// thread.
base::MessageLoop* const ui_message_loop_;
// Source that generates the PrintedPage's (i.e. a WebContents). It will be // Source that generates the PrintedPage's (i.e. a WebContents). It will be
// set back to NULL if the source is deleted before this object. // set back to NULL if the source is deleted before this object.
PrintedPagesSource* source_; PrintedPagesSource* source_;

View file

@ -22,11 +22,6 @@ PrintQueriesQueue::~PrintQueriesQueue() {
queued_queries_.clear(); queued_queries_.clear();
} }
void PrintQueriesQueue::SetDestination(PrintDestinationInterface* destination) {
base::AutoLock lock(lock_);
destination_ = destination;
}
void PrintQueriesQueue::QueuePrinterQuery(PrinterQuery* job) { void PrintQueriesQueue::QueuePrinterQuery(PrinterQuery* job) {
base::AutoLock lock(lock_); base::AutoLock lock(lock_);
DCHECK(job); DCHECK(job);
@ -49,17 +44,27 @@ scoped_refptr<PrinterQuery> PrintQueriesQueue::PopPrinterQuery(
return NULL; return NULL;
} }
scoped_refptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery() { scoped_refptr<PrinterQuery> PrintQueriesQueue::CreatePrinterQuery(
scoped_refptr<PrinterQuery> job = new printing::PrinterQuery; int render_process_id,
base::AutoLock lock(lock_); int render_view_id) {
job->SetWorkerDestination(destination_); scoped_refptr<PrinterQuery> job =
new printing::PrinterQuery(render_process_id, render_view_id);
return job; return job;
} }
void PrintQueriesQueue::Shutdown() { void PrintQueriesQueue::Shutdown() {
PrinterQueries queries_to_stop;
{
base::AutoLock lock(lock_); base::AutoLock lock(lock_);
queued_queries_.clear(); queued_queries_.swap(queries_to_stop);
destination_ = NULL; }
// Stop all pending queries, requests to generate print preview do not have
// corresponding PrintJob, so any pending preview requests are not covered
// by PrintJobManager::StopJobs and should be stopped explicitly.
for (PrinterQueries::iterator itr = queries_to_stop.begin();
itr != queries_to_stop.end(); ++itr) {
(*itr)->PostTask(FROM_HERE, base::Bind(&PrinterQuery::StopWorker, *itr));
}
} }
PrintJobManager::PrintJobManager() : is_shutdown_(false) { PrintJobManager::PrintJobManager() : is_shutdown_(false) {
@ -72,7 +77,7 @@ PrintJobManager::~PrintJobManager() {
scoped_refptr<PrintQueriesQueue> PrintJobManager::queue() { scoped_refptr<PrintQueriesQueue> PrintJobManager::queue() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!queue_) if (!queue_.get())
queue_ = new PrintQueriesQueue(); queue_ = new PrintQueriesQueue();
return queue_; return queue_;
} }
@ -83,7 +88,7 @@ void PrintJobManager::Shutdown() {
is_shutdown_ = true; is_shutdown_ = true;
registrar_.RemoveAll(); registrar_.RemoveAll();
StopJobs(true); StopJobs(true);
if (queue_) if (queue_.get())
queue_->Shutdown(); queue_->Shutdown();
queue_ = NULL; queue_ = NULL;
} }

View file

@ -10,11 +10,11 @@
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/synchronization/lock.h" #include "base/synchronization/lock.h"
#include "base/threading/non_thread_safe.h" #include "base/threading/non_thread_safe.h"
#include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_registrar.h"
#include "printing/print_destination_interface.h"
namespace printing { namespace printing {
@ -26,9 +26,6 @@ class PrintQueriesQueue : public base::RefCountedThreadSafe<PrintQueriesQueue> {
public: public:
PrintQueriesQueue(); PrintQueriesQueue();
// Sets the print destination to be set on the next print job.
void SetDestination(PrintDestinationInterface* destination);
// Queues a semi-initialized worker thread. Can be called from any thread. // Queues a semi-initialized worker thread. Can be called from any thread.
// Current use case is queuing from the I/O thread. // Current use case is queuing from the I/O thread.
// TODO(maruel): Have them vanish after a timeout (~5 minutes?) // TODO(maruel): Have them vanish after a timeout (~5 minutes?)
@ -39,7 +36,8 @@ class PrintQueriesQueue : public base::RefCountedThreadSafe<PrintQueriesQueue> {
scoped_refptr<PrinterQuery> PopPrinterQuery(int document_cookie); scoped_refptr<PrinterQuery> PopPrinterQuery(int document_cookie);
// Creates new query. // Creates new query.
scoped_refptr<PrinterQuery> CreatePrinterQuery(); scoped_refptr<PrinterQuery> CreatePrinterQuery(int render_process_id,
int render_view_id);
void Shutdown(); void Shutdown();
@ -54,8 +52,6 @@ class PrintQueriesQueue : public base::RefCountedThreadSafe<PrintQueriesQueue> {
PrinterQueries queued_queries_; PrinterQueries queued_queries_;
scoped_refptr<PrintDestinationInterface> destination_;
DISALLOW_COPY_AND_ASSIGN(PrintQueriesQueue); DISALLOW_COPY_AND_ASSIGN(PrintQueriesQueue);
}; };

View file

@ -13,10 +13,10 @@
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/printing/print_job.h" #include "chrome/browser/printing/print_job.h"
#include "chrome/browser/printing/printing_ui_web_contents_observer.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h" #include "content/public/browser/notification_service.h"
#include "grit/generated_resources.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "printing/print_job_constants.h" #include "printing/print_job_constants.h"
#include "printing/printed_document.h" #include "printing/printed_document.h"
#include "printing/printed_page.h" #include "printing/printed_page.h"
@ -25,6 +25,8 @@
using content::BrowserThread; using content::BrowserThread;
namespace printing {
namespace { namespace {
// Helper function to ensure |owner| is valid until at least |callback| returns. // Helper function to ensure |owner| is valid until at least |callback| returns.
@ -33,9 +35,41 @@ void HoldRefCallback(const scoped_refptr<printing::PrintJobWorkerOwner>& owner,
callback.Run(); callback.Run();
} }
} // namespace class PrintingContextDelegate : public PrintingContext::Delegate {
public:
PrintingContextDelegate(int render_process_id, int render_view_id);
virtual ~PrintingContextDelegate();
namespace printing { virtual gfx::NativeView GetParentView() OVERRIDE;
virtual std::string GetAppLocale() OVERRIDE;
private:
int render_process_id_;
int render_view_id_;
};
PrintingContextDelegate::PrintingContextDelegate(int render_process_id,
int render_view_id)
: render_process_id_(render_process_id),
render_view_id_(render_view_id) {
}
PrintingContextDelegate::~PrintingContextDelegate() {
}
gfx::NativeView PrintingContextDelegate::GetParentView() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::RenderViewHost* view =
content::RenderViewHost::FromID(render_process_id_, render_view_id_);
if (!view)
return NULL;
content::WebContents* wc = content::WebContents::FromRenderViewHost(view);
return wc ? wc->GetNativeView() : NULL;
}
std::string PrintingContextDelegate::GetAppLocale() {
return g_browser_process->GetApplicationLocale();
}
void NotificationCallback(PrintJobWorkerOwner* print_job, void NotificationCallback(PrintJobWorkerOwner* print_job,
JobEventDetails::Type detail_type, JobEventDetails::Type detail_type,
@ -49,22 +83,25 @@ void NotificationCallback(PrintJobWorkerOwner* print_job,
content::Details<JobEventDetails>(details)); content::Details<JobEventDetails>(details));
} }
PrintJobWorker::PrintJobWorker(PrintJobWorkerOwner* owner) } // namespace
: Thread("Printing_Worker"),
owner_(owner),
weak_factory_(this) {
// The object is created in the IO thread.
DCHECK_EQ(owner_->message_loop(), base::MessageLoop::current());
printing_context_.reset(PrintingContext::Create( PrintJobWorker::PrintJobWorker(int render_process_id,
g_browser_process->GetApplicationLocale())); int render_view_id,
PrintJobWorkerOwner* owner)
: owner_(owner), thread_("Printing_Worker"), weak_factory_(this) {
// The object is created in the IO thread.
DCHECK(owner_->RunsTasksOnCurrentThread());
printing_context_delegate_.reset(
new PrintingContextDelegate(render_process_id, render_view_id));
printing_context_ = PrintingContext::Create(printing_context_delegate_.get());
} }
PrintJobWorker::~PrintJobWorker() { PrintJobWorker::~PrintJobWorker() {
// The object is normally deleted in the UI thread, but when the user // The object is normally deleted in the UI thread, but when the user
// cancels printing or in the case of print preview, the worker is destroyed // cancels printing or in the case of print preview, the worker is destroyed
// on the I/O thread. // on the I/O thread.
DCHECK_EQ(owner_->message_loop(), base::MessageLoop::current()); DCHECK(owner_->RunsTasksOnCurrentThread());
Stop(); Stop();
} }
@ -73,18 +110,12 @@ void PrintJobWorker::SetNewOwner(PrintJobWorkerOwner* new_owner) {
owner_ = new_owner; owner_ = new_owner;
} }
void PrintJobWorker::SetPrintDestination(
PrintDestinationInterface* destination) {
destination_ = destination;
}
void PrintJobWorker::GetSettings( void PrintJobWorker::GetSettings(
bool ask_user_for_settings, bool ask_user_for_settings,
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int document_page_count, int document_page_count,
bool has_selection, bool has_selection,
MarginType margin_type) { MarginType margin_type) {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK_EQ(page_number_, PageNumber::npos()); DCHECK_EQ(page_number_, PageNumber::npos());
// Recursive task processing is needed for the dialog in case it needs to be // Recursive task processing is needed for the dialog in case it needs to be
@ -97,13 +128,12 @@ void PrintJobWorker::GetSettings(
// When we delegate to a destination, we don't ask the user for settings. // When we delegate to a destination, we don't ask the user for settings.
// TODO(mad): Ask the destination for settings. // TODO(mad): Ask the destination for settings.
if (ask_user_for_settings && destination_.get() == NULL) { if (ask_user_for_settings) {
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE, BrowserThread::UI, FROM_HERE,
base::Bind(&HoldRefCallback, make_scoped_refptr(owner_), base::Bind(&HoldRefCallback, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsWithUI, base::Bind(&PrintJobWorker::GetSettingsWithUI,
base::Unretained(this), base::Unretained(this),
base::Passed(&web_contents_observer),
document_page_count, document_page_count,
has_selection))); has_selection)));
} else { } else {
@ -116,8 +146,8 @@ void PrintJobWorker::GetSettings(
} }
void PrintJobWorker::SetSettings( void PrintJobWorker::SetSettings(
const base::DictionaryValue* const new_settings) { scoped_ptr<base::DictionaryValue> new_settings) {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::UI, BrowserThread::UI,
@ -126,11 +156,12 @@ void PrintJobWorker::SetSettings(
make_scoped_refptr(owner_), make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::UpdatePrintSettings, base::Bind(&PrintJobWorker::UpdatePrintSettings,
base::Unretained(this), base::Unretained(this),
base::Owned(new_settings)))); base::Passed(&new_settings))));
} }
void PrintJobWorker::UpdatePrintSettings( void PrintJobWorker::UpdatePrintSettings(
const base::DictionaryValue* const new_settings) { scoped_ptr<base::DictionaryValue> new_settings) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrintingContext::Result result = PrintingContext::Result result =
printing_context_->UpdatePrintSettings(*new_settings); printing_context_->UpdatePrintSettings(*new_settings);
GetSettingsDone(result); GetSettingsDone(result);
@ -147,36 +178,31 @@ void PrintJobWorker::GetSettingsDone(PrintingContext::Result result) {
// We can't use OnFailure() here since owner_ may not support notifications. // We can't use OnFailure() here since owner_ may not support notifications.
// PrintJob will create the new PrintedDocument. // PrintJob will create the new PrintedDocument.
owner_->message_loop()->PostTask( owner_->PostTask(FROM_HERE,
FROM_HERE,
base::Bind(&PrintJobWorkerOwner::GetSettingsDone, base::Bind(&PrintJobWorkerOwner::GetSettingsDone,
make_scoped_refptr(owner_), printing_context_->settings(), make_scoped_refptr(owner_),
printing_context_->settings(),
result)); result));
} }
void PrintJobWorker::GetSettingsWithUI( void PrintJobWorker::GetSettingsWithUI(
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int document_page_count, int document_page_count,
bool has_selection) { bool has_selection) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
gfx::NativeView parent_view = web_contents_observer->GetParentView();
if (!parent_view) {
GetSettingsWithUIDone(printing::PrintingContext::FAILED);
return;
}
printing_context_->AskUserForSettings( printing_context_->AskUserForSettings(
parent_view, document_page_count, has_selection, document_page_count,
has_selection,
base::Bind(&PrintJobWorker::GetSettingsWithUIDone, base::Bind(&PrintJobWorker::GetSettingsWithUIDone,
base::Unretained(this))); base::Unretained(this)));
} }
void PrintJobWorker::GetSettingsWithUIDone(PrintingContext::Result result) { void PrintJobWorker::GetSettingsWithUIDone(PrintingContext::Result result) {
message_loop()->PostTask( PostTask(FROM_HERE,
FROM_HERE, base::Bind(&HoldRefCallback,
base::Bind(&HoldRefCallback, make_scoped_refptr(owner_), make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone, base::Bind(&PrintJobWorker::GetSettingsDone,
base::Unretained(this), result))); base::Unretained(this),
result)));
} }
void PrintJobWorker::UseDefaultSettings() { void PrintJobWorker::UseDefaultSettings() {
@ -185,9 +211,9 @@ void PrintJobWorker::UseDefaultSettings() {
} }
void PrintJobWorker::StartPrinting(PrintedDocument* new_document) { void PrintJobWorker::StartPrinting(PrintedDocument* new_document) {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK_EQ(page_number_, PageNumber::npos()); DCHECK_EQ(page_number_, PageNumber::npos());
DCHECK_EQ(document_, new_document); DCHECK_EQ(document_.get(), new_document);
DCHECK(document_.get()); DCHECK(document_.get());
if (!document_.get() || page_number_ != PageNumber::npos() || if (!document_.get() || page_number_ != PageNumber::npos() ||
@ -216,7 +242,7 @@ void PrintJobWorker::StartPrinting(PrintedDocument* new_document) {
} }
void PrintJobWorker::OnDocumentChanged(PrintedDocument* new_document) { void PrintJobWorker::OnDocumentChanged(PrintedDocument* new_document) {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK_EQ(page_number_, PageNumber::npos()); DCHECK_EQ(page_number_, PageNumber::npos());
if (page_number_ != PageNumber::npos()) if (page_number_ != PageNumber::npos())
@ -230,7 +256,7 @@ void PrintJobWorker::OnNewPage() {
return; return;
// message_loop() could return NULL when the print job is cancelled. // message_loop() could return NULL when the print job is cancelled.
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
if (page_number_ == PageNumber::npos()) { if (page_number_ == PageNumber::npos()) {
// Find first page to print. // Find first page to print.
@ -243,15 +269,13 @@ void PrintJobWorker::OnNewPage() {
} }
// We have enough information to initialize page_number_. // We have enough information to initialize page_number_.
page_number_.Init(document_->settings(), page_count); page_number_.Init(document_->settings(), page_count);
if (destination_.get() != NULL)
destination_->SetPageCount(page_count);
} }
DCHECK_NE(page_number_, PageNumber::npos()); DCHECK_NE(page_number_, PageNumber::npos());
while (true) { while (true) {
// Is the page available? // Is the page available?
scoped_refptr<PrintedPage> page = document_->GetPage(page_number_.ToInt()); scoped_refptr<PrintedPage> page = document_->GetPage(page_number_.ToInt());
if (!page) { if (!page.get()) {
// We need to wait for the page to be available. // We need to wait for the page to be available.
base::MessageLoop::current()->PostDelayedTask( base::MessageLoop::current()->PostDelayedTask(
FROM_HERE, FROM_HERE,
@ -277,8 +301,33 @@ void PrintJobWorker::Cancel() {
// context we run. // context we run.
} }
bool PrintJobWorker::IsRunning() const {
return thread_.IsRunning();
}
bool PrintJobWorker::PostTask(const tracked_objects::Location& from_here,
const base::Closure& task) {
if (task_runner_.get())
return task_runner_->PostTask(from_here, task);
return false;
}
void PrintJobWorker::StopSoon() {
thread_.StopSoon();
}
void PrintJobWorker::Stop() {
thread_.Stop();
}
bool PrintJobWorker::Start() {
bool result = thread_.Start();
task_runner_ = thread_.task_runner();
return result;
}
void PrintJobWorker::OnDocumentDone() { void PrintJobWorker::OnDocumentDone() {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK_EQ(page_number_, PageNumber::npos()); DCHECK_EQ(page_number_, PageNumber::npos());
DCHECK(document_.get()); DCHECK(document_.get());
@ -287,9 +336,11 @@ void PrintJobWorker::OnDocumentDone() {
return; return;
} }
owner_->message_loop()->PostTask( owner_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(NotificationCallback, make_scoped_refptr(owner_), base::Bind(&NotificationCallback,
JobEventDetails::DOC_DONE, document_, make_scoped_refptr(owner_),
JobEventDetails::DOC_DONE,
document_,
scoped_refptr<PrintedPage>())); scoped_refptr<PrintedPage>()));
// Makes sure the variables are reinitialized. // Makes sure the variables are reinitialized.
@ -297,13 +348,15 @@ void PrintJobWorker::OnDocumentDone() {
} }
void PrintJobWorker::SpoolPage(PrintedPage* page) { void PrintJobWorker::SpoolPage(PrintedPage* page) {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
DCHECK_NE(page_number_, PageNumber::npos()); DCHECK_NE(page_number_, PageNumber::npos());
// Signal everyone that the page is about to be printed. // Signal everyone that the page is about to be printed.
owner_->message_loop()->PostTask( owner_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(NotificationCallback, make_scoped_refptr(owner_), base::Bind(&NotificationCallback,
JobEventDetails::NEW_PAGE, document_, make_scoped_refptr(owner_),
JobEventDetails::NEW_PAGE,
document_,
make_scoped_refptr(page))); make_scoped_refptr(page)));
// Preprocess. // Preprocess.
@ -312,18 +365,6 @@ void PrintJobWorker::SpoolPage(PrintedPage* page) {
return; return;
} }
if (destination_.get() != NULL) {
std::vector<uint8> metabytes(page->metafile()->GetDataSize());
bool success = page->metafile()->GetData(
reinterpret_cast<void*>(&metabytes[0]), metabytes.size());
DCHECK(success) << "Failed to get metafile data.";
destination_->SetPageContent(
page->page_number(),
reinterpret_cast<void*>(&metabytes[0]),
metabytes.size());
return;
}
// Actual printing. // Actual printing.
#if defined(OS_WIN) || defined(OS_MACOSX) #if defined(OS_WIN) || defined(OS_MACOSX)
document_->RenderPrintedPage(*page, printing_context_->context()); document_->RenderPrintedPage(*page, printing_context_->context());
@ -338,22 +379,25 @@ void PrintJobWorker::SpoolPage(PrintedPage* page) {
} }
// Signal everyone that the page is printed. // Signal everyone that the page is printed.
owner_->message_loop()->PostTask( owner_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(&NotificationCallback,
base::Bind(NotificationCallback, make_scoped_refptr(owner_), make_scoped_refptr(owner_),
JobEventDetails::PAGE_DONE, document_, JobEventDetails::PAGE_DONE,
document_,
make_scoped_refptr(page))); make_scoped_refptr(page)));
} }
void PrintJobWorker::OnFailure() { void PrintJobWorker::OnFailure() {
DCHECK_EQ(message_loop(), base::MessageLoop::current()); DCHECK(task_runner_->RunsTasksOnCurrentThread());
// We may loose our last reference by broadcasting the FAILED event. // We may loose our last reference by broadcasting the FAILED event.
scoped_refptr<PrintJobWorkerOwner> handle(owner_); scoped_refptr<PrintJobWorkerOwner> handle(owner_);
owner_->message_loop()->PostTask( owner_->PostTask(FROM_HERE,
FROM_HERE, base::Bind(NotificationCallback, make_scoped_refptr(owner_), base::Bind(&NotificationCallback,
JobEventDetails::FAILED, document_, make_scoped_refptr(owner_),
JobEventDetails::FAILED,
document_,
scoped_refptr<PrintedPage>())); scoped_refptr<PrintedPage>()));
Cancel(); Cancel();

View file

@ -9,12 +9,10 @@
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/threading/thread.h" #include "base/threading/thread.h"
#include "content/public/browser/browser_thread.h"
#include "printing/page_number.h" #include "printing/page_number.h"
#include "printing/print_destination_interface.h"
#include "printing/printing_context.h"
#include "printing/print_job_constants.h" #include "printing/print_job_constants.h"
#include "printing/printing_context.h"
class PrintingUIWebContentsObserver;
namespace base { namespace base {
class DictionaryValue; class DictionaryValue;
@ -22,39 +20,35 @@ class DictionaryValue;
namespace printing { namespace printing {
class PrintedDocument;
class PrintedPage;
class PrintJob; class PrintJob;
class PrintJobWorkerOwner; class PrintJobWorkerOwner;
class PrintedDocument;
class PrintedPage;
// Worker thread code. It manages the PrintingContext, which can be blocking // Worker thread code. It manages the PrintingContext, which can be blocking
// and/or run a message loop. This is the object that generates most // and/or run a message loop. This is the object that generates most
// NOTIFY_PRINT_JOB_EVENT notifications, but they are generated through a // NOTIFY_PRINT_JOB_EVENT notifications, but they are generated through a
// NotificationTask task to be executed from the right thread, the UI thread. // NotificationTask task to be executed from the right thread, the UI thread.
// PrintJob always outlives its worker instance. // PrintJob always outlives its worker instance.
class PrintJobWorker : public base::Thread { class PrintJobWorker {
public: public:
explicit PrintJobWorker(PrintJobWorkerOwner* owner); PrintJobWorker(int render_process_id,
int render_view_id,
PrintJobWorkerOwner* owner);
virtual ~PrintJobWorker(); virtual ~PrintJobWorker();
void SetNewOwner(PrintJobWorkerOwner* new_owner); void SetNewOwner(PrintJobWorkerOwner* new_owner);
// Set a destination for print.
// This supercedes the document's rendering destination.
void SetPrintDestination(PrintDestinationInterface* destination);
// Initializes the print settings. If |ask_user_for_settings| is true, a // Initializes the print settings. If |ask_user_for_settings| is true, a
// Print... dialog box will be shown to ask the user his preference. // Print... dialog box will be shown to ask the user his preference.
void GetSettings( void GetSettings(
bool ask_user_for_settings, bool ask_user_for_settings,
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int document_page_count, int document_page_count,
bool has_selection, bool has_selection,
MarginType margin_type); MarginType margin_type);
// Set the new print settings. This function takes ownership of // Set the new print settings.
// |new_settings|. void SetSettings(scoped_ptr<base::DictionaryValue> new_settings);
void SetSettings(const base::DictionaryValue* const new_settings);
// Starts the printing loop. Every pages are printed as soon as the data is // Starts the printing loop. Every pages are printed as soon as the data is
// available. Makes sure the new_document is the right one. // available. Makes sure the new_document is the right one.
@ -71,6 +65,22 @@ class PrintJobWorker : public base::Thread {
// This is the only function that can be called in a thread. // This is the only function that can be called in a thread.
void Cancel(); void Cancel();
// Returns true if the thread has been started, and not yet stopped.
bool IsRunning() const;
// Posts the given task to be run.
bool PostTask(const tracked_objects::Location& from_here,
const base::Closure& task);
// Signals the thread to exit in the near future.
void StopSoon();
// Signals the thread to exit and returns once the thread has exited.
void Stop();
// Starts the thread.
bool Start();
protected: protected:
// Retrieves the context for testing only. // Retrieves the context for testing only.
PrintingContext* printing_context() { return printing_context_.get(); } PrintingContext* printing_context() { return printing_context_.get(); }
@ -97,7 +107,6 @@ class PrintJobWorker : public base::Thread {
// Required on Mac and Linux. Windows can display UI from non-main threads, // Required on Mac and Linux. Windows can display UI from non-main threads,
// but sticks with this for consistency. // but sticks with this for consistency.
void GetSettingsWithUI( void GetSettingsWithUI(
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int document_page_count, int document_page_count,
bool has_selection); bool has_selection);
@ -106,9 +115,8 @@ class PrintJobWorker : public base::Thread {
// back into the IO thread for GetSettingsDone(). // back into the IO thread for GetSettingsDone().
void GetSettingsWithUIDone(PrintingContext::Result result); void GetSettingsWithUIDone(PrintingContext::Result result);
// Called on the UI thread to update the print settings. This function takes // Called on the UI thread to update the print settings.
// the ownership of |new_settings|. void UpdatePrintSettings(scoped_ptr<base::DictionaryValue> new_settings);
void UpdatePrintSettings(const base::DictionaryValue* const new_settings);
// Reports settings back to owner_. // Reports settings back to owner_.
void GetSettingsDone(PrintingContext::Result result); void GetSettingsDone(PrintingContext::Result result);
@ -118,15 +126,15 @@ class PrintJobWorker : public base::Thread {
// systems. // systems.
void UseDefaultSettings(); void UseDefaultSettings();
// Printing context delegate.
scoped_ptr<PrintingContext::Delegate> printing_context_delegate_;
// Information about the printer setting. // Information about the printer setting.
scoped_ptr<PrintingContext> printing_context_; scoped_ptr<PrintingContext> printing_context_;
// The printed document. Only has read-only access. // The printed document. Only has read-only access.
scoped_refptr<PrintedDocument> document_; scoped_refptr<PrintedDocument> document_;
// The print destination, may be NULL.
scoped_refptr<PrintDestinationInterface> destination_;
// The print job owning this worker thread. It is guaranteed to outlive this // The print job owning this worker thread. It is guaranteed to outlive this
// object. // object.
PrintJobWorkerOwner* owner_; PrintJobWorkerOwner* owner_;
@ -134,6 +142,12 @@ class PrintJobWorker : public base::Thread {
// Current page number to print. // Current page number to print.
PageNumber page_number_; PageNumber page_number_;
// Thread to run worker tasks.
base::Thread thread_;
// Tread-safe pointer to task runner of the |thread_|.
scoped_refptr<base::SequencedTaskRunner> task_runner_;
// Used to generate a WeakPtr for callbacks. // Used to generate a WeakPtr for callbacks.
base::WeakPtrFactory<PrintJobWorker> weak_factory_; base::WeakPtrFactory<PrintJobWorker> weak_factory_;

View file

@ -0,0 +1,27 @@
// 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 "chrome/browser/printing/print_job_worker_owner.h"
#include "base/message_loop/message_loop.h"
namespace printing {
PrintJobWorkerOwner::PrintJobWorkerOwner()
: task_runner_(base::MessageLoop::current()->task_runner()) {
}
PrintJobWorkerOwner::~PrintJobWorkerOwner() {
}
bool PrintJobWorkerOwner::RunsTasksOnCurrentThread() const {
return task_runner_->RunsTasksOnCurrentThread();
}
bool PrintJobWorkerOwner::PostTask(const tracked_objects::Location& from_here,
const base::Closure& task) {
return task_runner_->PostTask(from_here, task);
}
} // namespace printing

View file

@ -10,8 +10,12 @@
namespace base { namespace base {
class MessageLoop; class MessageLoop;
class SequencedTaskRunner;
} }
namespace tracked_objects {
class Location;
}
namespace printing { namespace printing {
@ -21,6 +25,8 @@ class PrintSettings;
class PrintJobWorkerOwner class PrintJobWorkerOwner
: public base::RefCountedThreadSafe<PrintJobWorkerOwner> { : public base::RefCountedThreadSafe<PrintJobWorkerOwner> {
public: public:
PrintJobWorkerOwner();
// Finishes the initialization began by PrintJobWorker::GetSettings(). // Finishes the initialization began by PrintJobWorker::GetSettings().
// Creates a new PrintedDocument if necessary. Solely meant to be called by // Creates a new PrintedDocument if necessary. Solely meant to be called by
// PrintJobWorker. // PrintJobWorker.
@ -30,19 +36,29 @@ class PrintJobWorkerOwner
// Detach the PrintJobWorker associated to this object. // Detach the PrintJobWorker associated to this object.
virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) = 0; virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) = 0;
// Retrieves the message loop that is expected to process GetSettingsDone.
virtual base::MessageLoop* message_loop() = 0;
// Access the current settings. // Access the current settings.
virtual const PrintSettings& settings() const = 0; virtual const PrintSettings& settings() const = 0;
// Cookie uniquely identifying the PrintedDocument and/or loaded settings. // Cookie uniquely identifying the PrintedDocument and/or loaded settings.
virtual int cookie() const = 0; virtual int cookie() const = 0;
// Returns true if the current thread is a thread on which a task
// may be run, and false if no task will be run on the current
// thread.
bool RunsTasksOnCurrentThread() const;
// Posts the given task to be run.
bool PostTask(const tracked_objects::Location& from_here,
const base::Closure& task);
protected: protected:
friend class base::RefCountedThreadSafe<PrintJobWorkerOwner>; friend class base::RefCountedThreadSafe<PrintJobWorkerOwner>;
virtual ~PrintJobWorkerOwner() {} virtual ~PrintJobWorkerOwner();
// Task runner reference. Used to send notifications in the right
// thread.
scoped_refptr<base::SequencedTaskRunner> task_runner_;
}; };
} // namespace printing } // namespace printing

View file

@ -24,11 +24,14 @@
#include "content/public/browser/notification_source.h" #include "content/public/browser/notification_source.h"
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h" #include "printing/pdf_metafile_skia.h"
#include "printing/metafile_impl.h"
#include "printing/printed_document.h" #include "printing/printed_document.h"
#include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util.h"
#if defined(ENABLE_FULL_PRINTING)
#include "chrome/browser/printing/print_error_dialog.h"
#endif
using base::TimeDelta; using base::TimeDelta;
using content::BrowserThread; using content::BrowserThread;
@ -36,11 +39,6 @@ namespace printing {
namespace { namespace {
#if defined(OS_WIN) && !defined(WIN_PDF_METAFILE_FOR_PRINTING)
// Limits memory usage by raster to 64 MiB.
const int kMaxRasterSizeInPixels = 16*1024*1024;
#endif
} // namespace } // namespace
PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
@ -50,11 +48,10 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents)
inside_inner_message_loop_(false), inside_inner_message_loop_(false),
cookie_(0), cookie_(0),
queue_(g_browser_process->print_job_manager()->queue()) { queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_); DCHECK(queue_.get());
#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || \ #if !defined(OS_MACOSX)
defined(WIN_PDF_METAFILE_FOR_PRINTING)
expecting_first_page_ = true; expecting_first_page_ = true;
#endif #endif // OS_MACOSX
printing_enabled_ = true; printing_enabled_ = true;
} }
@ -63,10 +60,12 @@ PrintViewManagerBase::~PrintViewManagerBase() {
DisconnectFromCurrentPrintJob(); DisconnectFromCurrentPrintJob();
} }
#if !defined(DISABLE_BASIC_PRINTING)
bool PrintViewManagerBase::PrintNow(bool silent, bool print_background) { bool PrintViewManagerBase::PrintNow(bool silent, bool print_background) {
return PrintNowInternal(new PrintMsg_PrintPages( return PrintNowInternal(new PrintMsg_PrintPages(
routing_id(), silent, print_background)); routing_id(), silent, print_background));
} }
#endif // !DISABLE_BASIC_PRINTING
void PrintViewManagerBase::NavigationStopped() { void PrintViewManagerBase::NavigationStopped() {
// Cancel the current job, wait for the worker to finish. // Cancel the current job, wait for the worker to finish.
@ -117,13 +116,12 @@ void PrintViewManagerBase::OnDidPrintPage(
return; return;
} }
#if (defined(OS_WIN) && !defined(WIN_PDF_METAFILE_FOR_PRINTING)) || \ #if defined(OS_MACOSX)
defined(OS_MACOSX)
const bool metafile_must_be_valid = true; const bool metafile_must_be_valid = true;
#elif defined(OS_POSIX) || defined(WIN_PDF_METAFILE_FOR_PRINTING) #else
const bool metafile_must_be_valid = expecting_first_page_; const bool metafile_must_be_valid = expecting_first_page_;
expecting_first_page_ = false; expecting_first_page_ = false;
#endif #endif // OS_MACOSX
base::SharedMemory shared_buf(params.metafile_data_handle, true); base::SharedMemory shared_buf(params.metafile_data_handle, true);
if (metafile_must_be_valid) { if (metafile_must_be_valid) {
@ -134,7 +132,7 @@ void PrintViewManagerBase::OnDidPrintPage(
} }
} }
scoped_ptr<NativeMetafile> metafile(new NativeMetafile); scoped_ptr<PdfMetafileSkia> metafile(new PdfMetafileSkia);
if (metafile_must_be_valid) { if (metafile_must_be_valid) {
if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) { if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) {
NOTREACHED() << "Invalid metafile header"; NOTREACHED() << "Invalid metafile header";
@ -143,32 +141,10 @@ void PrintViewManagerBase::OnDidPrintPage(
} }
} }
#if defined(OS_WIN) && !defined(WIN_PDF_METAFILE_FOR_PRINTING) #if !defined(OS_WIN)
bool big_emf = (params.data_size && params.data_size >= kMetafileMaxSize);
int raster_size =
std::min(params.page_size.GetArea(), kMaxRasterSizeInPixels);
if (big_emf) {
scoped_ptr<NativeMetafile> raster_metafile(
metafile->RasterizeMetafile(raster_size));
if (raster_metafile.get()) {
metafile.swap(raster_metafile);
} else if (big_emf) {
// Don't fall back to emf here.
NOTREACHED() << "size:" << params.data_size;
TerminatePrintJob(true);
web_contents()->Stop();
return;
}
}
#endif // OS_WIN && !WIN_PDF_METAFILE_FOR_PRINTING
#if !defined(WIN_PDF_METAFILE_FOR_PRINTING)
// Update the rendered document. It will send notifications to the listener. // Update the rendered document. It will send notifications to the listener.
document->SetPage(params.page_number, document->SetPage(params.page_number,
metafile.release(), metafile.PassAs<MetafilePlayer>(),
#if defined(OS_WIN)
params.actual_shrink,
#endif // OS_WIN
params.page_size, params.page_size,
params.content_area); params.content_area);
@ -180,19 +156,8 @@ void PrintViewManagerBase::OnDidPrintPage(
params.data_size); params.data_size);
document->DebugDumpData(bytes, FILE_PATH_LITERAL(".pdf")); document->DebugDumpData(bytes, FILE_PATH_LITERAL(".pdf"));
if (!pdf_to_emf_converter_)
pdf_to_emf_converter_ = PdfToEmfConverter::CreateDefault();
const int kPrinterDpi = print_job_->settings().dpi();
pdf_to_emf_converter_->Start(
bytes,
printing::PdfRenderSettings(params.content_area, kPrinterDpi, true),
base::Bind(&PrintViewManagerBase::OnPdfToEmfConverted,
base::Unretained(this),
params));
} }
#endif // !WIN_PDF_METAFILE_FOR_PRINTING #endif // !OS_WIN
} }
void PrintViewManagerBase::OnPrintingFailed(int cookie) { void PrintViewManagerBase::OnPrintingFailed(int cookie) {
@ -386,10 +351,9 @@ void PrintViewManagerBase::DisconnectFromCurrentPrintJob() {
// DO NOT wait for the job to finish. // DO NOT wait for the job to finish.
ReleasePrintJob(); ReleasePrintJob();
} }
#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || \ #if !defined(OS_MACOSX)
defined(WIN_PDF_METAFILE_FOR_PRINTING)
expecting_first_page_ = true; expecting_first_page_ = true;
#endif #endif // OS_MACOSX
} }
void PrintViewManagerBase::PrintingDone(bool success) { void PrintViewManagerBase::PrintingDone(bool success) {
@ -481,12 +445,12 @@ bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
// The job was initiated by a script. Time to get the corresponding worker // The job was initiated by a script. Time to get the corresponding worker
// thread. // thread.
scoped_refptr<PrinterQuery> queued_query = queue_->PopPrinterQuery(cookie); scoped_refptr<PrinterQuery> queued_query = queue_->PopPrinterQuery(cookie);
if (!queued_query) { if (!queued_query.get()) {
NOTREACHED(); NOTREACHED();
return false; return false;
} }
if (!CreateNewPrintJob(queued_query)) { if (!CreateNewPrintJob(queued_query.get())) {
// Don't kill anything. // Don't kill anything.
return false; return false;
} }
@ -512,8 +476,6 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
int cookie = cookie_; int cookie = cookie_;
cookie_ = 0; cookie_ = 0;
queue_->SetDestination(NULL);
printing::PrintJobManager* print_job_manager = printing::PrintJobManager* print_job_manager =
g_browser_process->print_job_manager(); g_browser_process->print_job_manager();
@ -523,7 +485,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
scoped_refptr<printing::PrinterQuery> printer_query; scoped_refptr<printing::PrinterQuery> printer_query;
printer_query = queue_->PopPrinterQuery(cookie); printer_query = queue_->PopPrinterQuery(cookie);
if (!printer_query) if (!printer_query.get())
return; return;
BrowserThread::PostTask( BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE, BrowserThread::IO, FROM_HERE,

View file

@ -23,7 +23,7 @@ class RenderViewHost;
namespace printing { namespace printing {
class JobEventDetails; class JobEventDetails;
class PdfToEmfConverter; class MetafilePlayer;
class PrintJob; class PrintJob;
class PrintJobWorkerOwner; class PrintJobWorkerOwner;
class PrintQueriesQueue; class PrintQueriesQueue;
@ -35,10 +35,12 @@ class PrintViewManagerBase : public content::NotificationObserver,
public: public:
virtual ~PrintViewManagerBase(); virtual ~PrintViewManagerBase();
#if !defined(DISABLE_BASIC_PRINTING)
// Prints the current document immediately. Since the rendering is // Prints the current document immediately. Since the rendering is
// asynchronous, the actual printing will not be completed on the return of // asynchronous, the actual printing will not be completed on the return of
// this function. Returns false if printing is impossible at the moment. // this function. Returns false if printing is impossible at the moment.
virtual bool PrintNow(bool silent, bool print_background); virtual bool PrintNow(bool silent, bool print_background);
#endif // !DISABLE_BASIC_PRINTING
// PrintedPagesSource implementation. // PrintedPagesSource implementation.
virtual base::string16 RenderSourceName() OVERRIDE; virtual base::string16 RenderSourceName() OVERRIDE;
@ -140,11 +142,10 @@ class PrintViewManagerBase : public content::NotificationObserver,
// print settings are being loaded. // print settings are being loaded.
bool inside_inner_message_loop_; bool inside_inner_message_loop_;
#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || \ #if !defined(OS_MACOSX)
defined(WIN_PDF_METAFILE_FOR_PRINTING)
// Set to true when OnDidPrintPage() should be expecting the first page. // Set to true when OnDidPrintPage() should be expecting the first page.
bool expecting_first_page_; bool expecting_first_page_;
#endif #endif // OS_MACOSX
// The document cookie of the current PrinterQuery. // The document cookie of the current PrinterQuery.
int cookie_; int cookie_;

View file

@ -10,13 +10,11 @@
#include "base/threading/thread_restrictions.h" #include "base/threading/thread_restrictions.h"
#include "base/values.h" #include "base/values.h"
#include "chrome/browser/printing/print_job_worker.h" #include "chrome/browser/printing/print_job_worker.h"
#include "chrome/browser/printing/printing_ui_web_contents_observer.h"
namespace printing { namespace printing {
PrinterQuery::PrinterQuery() PrinterQuery::PrinterQuery(int render_process_id, int render_view_id)
: io_message_loop_(base::MessageLoop::current()), : worker_(new PrintJobWorker(render_process_id, render_view_id, this)),
worker_(new PrintJobWorker(this)),
is_print_dialog_box_shown_(false), is_print_dialog_box_shown_(false),
cookie_(PrintSettings::NewCookie()), cookie_(PrintSettings::NewCookie()),
last_status_(PrintingContext::FAILED) { last_status_(PrintingContext::FAILED) {
@ -57,10 +55,6 @@ PrintJobWorker* PrinterQuery::DetachWorker(PrintJobWorkerOwner* new_owner) {
return worker_.release(); return worker_.release();
} }
base::MessageLoop* PrinterQuery::message_loop() {
return io_message_loop_;
}
const PrintSettings& PrinterQuery::settings() const { const PrintSettings& PrinterQuery::settings() const {
return settings_; return settings_;
} }
@ -71,43 +65,34 @@ int PrinterQuery::cookie() const {
void PrinterQuery::GetSettings( void PrinterQuery::GetSettings(
GetSettingsAskParam ask_user_for_settings, GetSettingsAskParam ask_user_for_settings,
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int expected_page_count, int expected_page_count,
bool has_selection, bool has_selection,
MarginType margin_type, MarginType margin_type,
const base::Closure& callback) { const base::Closure& callback) {
DCHECK_EQ(io_message_loop_, base::MessageLoop::current()); DCHECK(RunsTasksOnCurrentThread());
DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_print_dialog_box_shown_);
StartWorker(callback); StartWorker(callback);
// Real work is done in PrintJobWorker::GetSettings(). // Real work is done in PrintJobWorker::GetSettings().
is_print_dialog_box_shown_ = ask_user_for_settings == ASK_USER; is_print_dialog_box_shown_ = ask_user_for_settings == ASK_USER;
worker_->message_loop()->PostTask( worker_->PostTask(FROM_HERE,
FROM_HERE,
base::Bind(&PrintJobWorker::GetSettings, base::Bind(&PrintJobWorker::GetSettings,
base::Unretained(worker_.get()), base::Unretained(worker_.get()),
is_print_dialog_box_shown_, is_print_dialog_box_shown_,
base::Passed(&web_contents_observer),
expected_page_count, expected_page_count,
has_selection, has_selection,
margin_type)); margin_type));
} }
void PrinterQuery::SetSettings(const base::DictionaryValue& new_settings, void PrinterQuery::SetSettings(scoped_ptr<base::DictionaryValue> new_settings,
const base::Closure& callback) { const base::Closure& callback) {
StartWorker(callback); StartWorker(callback);
worker_->message_loop()->PostTask( worker_->PostTask(FROM_HERE,
FROM_HERE,
base::Bind(&PrintJobWorker::SetSettings, base::Bind(&PrintJobWorker::SetSettings,
base::Unretained(worker_.get()), base::Unretained(worker_.get()),
new_settings.DeepCopy())); base::Passed(&new_settings)));
}
void PrinterQuery::SetWorkerDestination(
PrintDestinationInterface* destination) {
worker_->SetPrintDestination(destination);
} }
void PrinterQuery::StartWorker(const base::Closure& callback) { void PrinterQuery::StartWorker(const base::Closure& callback) {
@ -115,7 +100,7 @@ void PrinterQuery::StartWorker(const base::Closure& callback) {
DCHECK(worker_.get()); DCHECK(worker_.get());
// Lazily create the worker thread. There is one worker thread per print job. // Lazily create the worker thread. There is one worker thread per print job.
if (!worker_->message_loop()) if (!worker_->IsRunning())
worker_->Start(); worker_->Start();
callback_ = callback; callback_ = callback;

View file

@ -11,11 +11,8 @@
#include "chrome/browser/printing/print_job_worker_owner.h" #include "chrome/browser/printing/print_job_worker_owner.h"
#include "printing/print_job_constants.h" #include "printing/print_job_constants.h"
class PrintingUIWebContentsObserver;
namespace base { namespace base {
class DictionaryValue; class DictionaryValue;
class MessageLoop;
} }
namespace printing { namespace printing {
@ -32,13 +29,12 @@ class PrinterQuery : public PrintJobWorkerOwner {
ASK_USER, ASK_USER,
}; };
PrinterQuery(); PrinterQuery(int render_process_id, int render_view_id);
// PrintJobWorkerOwner implementation. // PrintJobWorkerOwner implementation.
virtual void GetSettingsDone(const PrintSettings& new_settings, virtual void GetSettingsDone(const PrintSettings& new_settings,
PrintingContext::Result result) OVERRIDE; PrintingContext::Result result) OVERRIDE;
virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) OVERRIDE; virtual PrintJobWorker* DetachWorker(PrintJobWorkerOwner* new_owner) OVERRIDE;
virtual base::MessageLoop* message_loop() OVERRIDE;
virtual const PrintSettings& settings() const OVERRIDE; virtual const PrintSettings& settings() const OVERRIDE;
virtual int cookie() const OVERRIDE; virtual int cookie() const OVERRIDE;
@ -48,19 +44,15 @@ class PrinterQuery : public PrintJobWorkerOwner {
// |ask_for_user_settings| is DEFAULTS. // |ask_for_user_settings| is DEFAULTS.
void GetSettings( void GetSettings(
GetSettingsAskParam ask_user_for_settings, GetSettingsAskParam ask_user_for_settings,
scoped_ptr<PrintingUIWebContentsObserver> web_contents_observer,
int expected_page_count, int expected_page_count,
bool has_selection, bool has_selection,
MarginType margin_type, MarginType margin_type,
const base::Closure& callback); const base::Closure& callback);
// Updates the current settings with |new_settings| dictionary values. // Updates the current settings with |new_settings| dictionary values.
void SetSettings(const base::DictionaryValue& new_settings, void SetSettings(scoped_ptr<base::DictionaryValue> new_settings,
const base::Closure& callback); const base::Closure& callback);
// Set a destination for the worker.
void SetWorkerDestination(PrintDestinationInterface* destination);
// Stops the worker thread since the client is done with this object. // Stops the worker thread since the client is done with this object.
void StopWorker(); void StopWorker();
@ -78,10 +70,6 @@ class PrinterQuery : public PrintJobWorkerOwner {
// Lazy create the worker thread. There is one worker thread per print job. // Lazy create the worker thread. There is one worker thread per print job.
void StartWorker(const base::Closure& callback); void StartWorker(const base::Closure& callback);
// Main message loop reference. Used to send notifications in the right
// thread.
base::MessageLoop* const io_message_loop_;
// All the UI is done in a worker thread because many Win32 print functions // All the UI is done in a worker thread because many Win32 print functions
// are blocking and enters a message loop without your consent. There is one // are blocking and enters a message loop without your consent. There is one
// worker thread per print job. // worker thread per print job.

View file

@ -8,21 +8,56 @@
#include "base/bind.h" #include "base/bind.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/printing/print_job_manager.h"
#include "chrome/browser/printing/printing_ui_web_contents_observer.h" #include "chrome/browser/printing/printer_query.h"
#include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/common/print_messages.h" #include "chrome/common/print_messages.h"
#include "content/public/browser/browser_thread.h" #include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_view_host.h" #include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents.h"
#include "content/public/common/child_process_host.h"
#if defined(ENABLE_FULL_PRINTING)
#include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
#endif
#if defined(OS_CHROMEOS)
#include <fcntl.h>
#include <map>
#include "base/files/file_util.h"
#include "base/lazy_instance.h"
#include "chrome/browser/printing/print_dialog_cloud.h"
#endif
#if defined(OS_ANDROID)
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/printing/print_view_manager_basic.h"
#include "printing/printing_context_android.h"
#endif
using content::BrowserThread; using content::BrowserThread;
namespace printing {
namespace { namespace {
void RenderParamsFromPrintSettings(const printing::PrintSettings& settings, #if defined(OS_CHROMEOS)
typedef std::map<int, base::FilePath> SequenceToPathMap;
struct PrintingSequencePathMap {
SequenceToPathMap map;
int sequence;
};
// No locking, only access on the FILE thread.
static base::LazyInstance<PrintingSequencePathMap>
g_printing_file_descriptor_map = LAZY_INSTANCE_INITIALIZER;
#endif
void RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) { PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size(); params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize( params->content_size.SetSize(
@ -57,21 +92,45 @@ PrintingMessageFilter::PrintingMessageFilter(int render_process_id)
: BrowserMessageFilter(PrintMsgStart), : BrowserMessageFilter(PrintMsgStart),
render_process_id_(render_process_id), render_process_id_(render_process_id),
queue_(g_browser_process->print_job_manager()->queue()) { queue_(g_browser_process->print_job_manager()->queue()) {
DCHECK(queue_); DCHECK(queue_.get());
} }
PrintingMessageFilter::~PrintingMessageFilter() { PrintingMessageFilter::~PrintingMessageFilter() {
} }
void PrintingMessageFilter::OverrideThreadForMessage(
const IPC::Message& message, BrowserThread::ID* thread) {
#if defined(OS_CHROMEOS)
if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||
message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {
*thread = BrowserThread::FILE;
}
#elif defined(OS_ANDROID)
if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID ||
message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) {
*thread = BrowserThread::UI;
}
#endif
}
bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) { bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) {
bool handled = true; bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilter, message) IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilter, message)
#if defined(OS_WIN) #if defined(OS_WIN)
IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection) IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection)
#endif
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting,
OnAllocateTempFileForPrinting)
IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten,
OnTempFileForPrintingWritten)
#endif #endif
IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings, IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings,
OnGetDefaultPrintSettings) OnGetDefaultPrintSettings)
IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint) IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint)
#if defined(ENABLE_FULL_PRINTING)
IPC_MESSAGE_HANDLER(PrintHostMsg_CheckForCancel, OnCheckForCancel)
#endif
IPC_MESSAGE_UNHANDLED(handled = false) IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP() IPC_END_MESSAGE_MAP()
return handled; return handled;
@ -88,6 +147,102 @@ void PrintingMessageFilter::OnDuplicateSection(
} }
#endif #endif
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
void PrintingMessageFilter::OnAllocateTempFileForPrinting(
int render_view_id,
base::FileDescriptor* temp_file_fd,
int* sequence_number) {
#if defined(OS_CHROMEOS)
// TODO(thestig): Use |render_view_id| for Chrome OS.
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
temp_file_fd->fd = *sequence_number = -1;
temp_file_fd->auto_close = false;
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
*sequence_number = g_printing_file_descriptor_map.Get().sequence++;
base::FilePath path;
if (base::CreateTemporaryFile(&path)) {
int fd = open(path.value().c_str(), O_WRONLY);
if (fd >= 0) {
SequenceToPathMap::iterator it = map->find(*sequence_number);
if (it != map->end()) {
NOTREACHED() << "Sequence number already in use. seq=" <<
*sequence_number;
} else {
(*map)[*sequence_number] = path;
temp_file_fd->fd = fd;
temp_file_fd->auto_close = true;
}
}
}
#elif defined(OS_ANDROID)
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (!wc)
return;
PrintViewManagerBasic* print_view_manager =
PrintViewManagerBasic::FromWebContents(wc);
// The file descriptor is originally created in & passed from the Android
// side, and it will handle the closing.
const base::FileDescriptor& file_descriptor =
print_view_manager->file_descriptor();
temp_file_fd->fd = file_descriptor.fd;
temp_file_fd->auto_close = false;
#endif
}
void PrintingMessageFilter::OnTempFileForPrintingWritten(int render_view_id,
int sequence_number) {
#if defined(OS_CHROMEOS)
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map;
SequenceToPathMap::iterator it = map->find(sequence_number);
if (it == map->end()) {
NOTREACHED() << "Got a sequence that we didn't pass to the "
"renderer: " << sequence_number;
return;
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PrintingMessageFilter::CreatePrintDialogForFile,
this, render_view_id, it->second));
// Erase the entry in the map.
map->erase(it);
#elif defined(OS_ANDROID)
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (!wc)
return;
PrintViewManagerBasic* print_view_manager =
PrintViewManagerBasic::FromWebContents(wc);
const base::FileDescriptor& file_descriptor =
print_view_manager->file_descriptor();
PrintingContextAndroid::PdfWritingDone(file_descriptor.fd, true);
// Invalidate the file descriptor so it doesn't accidentally get reused.
print_view_manager->set_file_descriptor(base::FileDescriptor(-1, false));
#endif
}
#endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
void PrintingMessageFilter::CreatePrintDialogForFile(
int render_view_id,
const base::FilePath& path) {
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (!wc)
return;
print_dialog_cloud::CreatePrintDialogForFile(
wc->GetBrowserContext(),
wc->GetTopLevelNativeWindow(),
path,
wc->GetTitle(),
base::string16(),
std::string("application/pdf"));
}
#endif // defined(OS_CHROMEOS)
content::WebContents* PrintingMessageFilter::GetWebContentsForRenderView( content::WebContents* PrintingMessageFilter::GetWebContentsForRenderView(
int render_view_id) { int render_view_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CURRENTLY_ON(BrowserThread::UI);
@ -96,80 +251,41 @@ content::WebContents* PrintingMessageFilter::GetWebContentsForRenderView(
return view ? content::WebContents::FromRenderViewHost(view) : NULL; return view ? content::WebContents::FromRenderViewHost(view) : NULL;
} }
struct PrintingMessageFilter::GetPrintSettingsForRenderViewParams {
printing::PrinterQuery::GetSettingsAskParam ask_user_for_settings;
int expected_page_count;
bool has_selection;
printing::MarginType margin_type;
};
void PrintingMessageFilter::GetPrintSettingsForRenderView(
int render_view_id,
GetPrintSettingsForRenderViewParams params,
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (wc) {
scoped_ptr<PrintingUIWebContentsObserver> wc_observer(
new PrintingUIWebContentsObserver(wc));
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&printing::PrinterQuery::GetSettings, printer_query,
params.ask_user_for_settings, base::Passed(&wc_observer),
params.expected_page_count, params.has_selection,
params.margin_type, callback));
} else {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&PrintingMessageFilter::OnGetPrintSettingsFailed, this,
callback, printer_query));
}
}
void PrintingMessageFilter::OnGetPrintSettingsFailed(
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
printer_query->GetSettingsDone(printing::PrintSettings(),
printing::PrintingContext::FAILED);
callback.Run();
}
void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) { void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) {
DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_CURRENTLY_ON(BrowserThread::IO);
scoped_refptr<printing::PrinterQuery> printer_query; scoped_refptr<PrinterQuery> printer_query;
if (false) { #if 0
if (!profile_io_data_->printing_enabled()->GetValue()) {
// Reply with NULL query. // Reply with NULL query.
OnGetDefaultPrintSettingsReply(printer_query, reply_msg); OnGetDefaultPrintSettingsReply(printer_query, reply_msg);
return; return;
} }
#endif
printer_query = queue_->PopPrinterQuery(0); printer_query = queue_->PopPrinterQuery(0);
if (!printer_query) if (!printer_query.get()) {
printer_query = queue_->CreatePrinterQuery(); printer_query =
queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
}
// Loads default settings. This is asynchronous, only the IPC message sender // Loads default settings. This is asynchronous, only the IPC message sender
// will hang until the settings are retrieved. // will hang until the settings are retrieved.
GetPrintSettingsForRenderViewParams params; printer_query->GetSettings(
params.ask_user_for_settings = printing::PrinterQuery::DEFAULTS; PrinterQuery::DEFAULTS,
params.expected_page_count = 0; 0,
params.has_selection = false; false,
params.margin_type = printing::DEFAULT_MARGINS; DEFAULT_MARGINS,
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this,
reply_msg->routing_id(), params,
base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply, base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply,
this, printer_query, reply_msg), this,
printer_query)); printer_query,
reply_msg));
} }
void PrintingMessageFilter::OnGetDefaultPrintSettingsReply( void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
scoped_refptr<printing::PrinterQuery> printer_query, scoped_refptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) { IPC::Message* reply_msg) {
PrintMsg_Print_Params params; PrintMsg_Print_Params params;
if (!printer_query.get() || if (!printer_query.get() ||
printer_query->last_status() != printing::PrintingContext::OK) { printer_query->last_status() != PrintingContext::OK) {
params.Reset(); params.Reset();
} else { } else {
RenderParamsFromPrintSettings(printer_query->settings(), &params); RenderParamsFromPrintSettings(printer_query->settings(), &params);
@ -191,43 +307,69 @@ void PrintingMessageFilter::OnGetDefaultPrintSettingsReply(
void PrintingMessageFilter::OnScriptedPrint( void PrintingMessageFilter::OnScriptedPrint(
const PrintHostMsg_ScriptedPrint_Params& params, const PrintHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg) { IPC::Message* reply_msg) {
scoped_refptr<printing::PrinterQuery> printer_query = scoped_refptr<PrinterQuery> printer_query =
queue_->PopPrinterQuery(params.cookie); queue_->PopPrinterQuery(params.cookie);
if (!printer_query) if (!printer_query.get()) {
printer_query = queue_->CreatePrinterQuery(); printer_query =
GetPrintSettingsForRenderViewParams settings_params; queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id());
settings_params.ask_user_for_settings = printing::PrinterQuery::ASK_USER; }
settings_params.expected_page_count = params.expected_pages_count; printer_query->GetSettings(
settings_params.has_selection = params.has_selection; PrinterQuery::ASK_USER,
settings_params.margin_type = params.margin_type; params.expected_pages_count,
params.has_selection,
BrowserThread::PostTask( params.margin_type,
BrowserThread::UI, FROM_HERE, base::Bind(&PrintingMessageFilter::OnScriptedPrintReply,
base::Bind(&PrintingMessageFilter::GetPrintSettingsForRenderView, this, this,
reply_msg->routing_id(), settings_params, printer_query,
base::Bind(&PrintingMessageFilter::OnScriptedPrintReply, this, reply_msg));
printer_query, reply_msg),
printer_query));
} }
void PrintingMessageFilter::OnScriptedPrintReply( void PrintingMessageFilter::OnScriptedPrintReply(
scoped_refptr<printing::PrinterQuery> printer_query, scoped_refptr<PrinterQuery> printer_query,
IPC::Message* reply_msg) { IPC::Message* reply_msg) {
PrintMsg_PrintPages_Params params; PrintMsg_PrintPages_Params params;
if (printer_query->last_status() != printing::PrintingContext::OK || #if defined(OS_ANDROID)
// We need to save the routing ID here because Send method below deletes the
// |reply_msg| before we can get the routing ID for the Android code.
int routing_id = reply_msg->routing_id();
#endif
if (printer_query->last_status() != PrintingContext::OK ||
!printer_query->settings().dpi()) { !printer_query->settings().dpi()) {
params.Reset(); params.Reset();
} else { } else {
RenderParamsFromPrintSettings(printer_query->settings(), &params.params); RenderParamsFromPrintSettings(printer_query->settings(), &params.params);
params.params.document_cookie = printer_query->cookie(); params.params.document_cookie = printer_query->cookie();
params.pages = params.pages = PageRange::GetPages(printer_query->settings().ranges());
printing::PageRange::GetPages(printer_query->settings().ranges());
} }
PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params); PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params);
Send(reply_msg); Send(reply_msg);
if (params.params.dpi && params.params.document_cookie) { if (params.params.dpi && params.params.document_cookie) {
#if defined(OS_ANDROID)
int file_descriptor;
const base::string16& device_name = printer_query->settings().device_name();
if (base::StringToInt(device_name, &file_descriptor)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&PrintingMessageFilter::UpdateFileDescriptor, this,
routing_id, file_descriptor));
}
#endif
queue_->QueuePrinterQuery(printer_query.get()); queue_->QueuePrinterQuery(printer_query.get());
} else { } else {
printer_query->StopWorker(); printer_query->StopWorker();
} }
} }
#if defined(OS_ANDROID)
void PrintingMessageFilter::UpdateFileDescriptor(int render_view_id, int fd) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::WebContents* wc = GetWebContentsForRenderView(render_view_id);
if (!wc)
return;
PrintViewManagerBasic* print_view_manager =
PrintViewManagerBasic::FromWebContents(wc);
print_view_manager->set_file_descriptor(base::FileDescriptor(fd, false));
}
#endif
} // namespace printing

View file

@ -15,6 +15,8 @@
#endif #endif
struct PrintHostMsg_ScriptedPrint_Params; struct PrintHostMsg_ScriptedPrint_Params;
class Profile;
class ProfileIOData;
namespace base { namespace base {
class DictionaryValue; class DictionaryValue;
@ -26,18 +28,21 @@ class WebContents;
} }
namespace printing { namespace printing {
class PrinterQuery;
class PrintJobManager; class PrintJobManager;
class PrintQueriesQueue; class PrintQueriesQueue;
} class PrinterQuery;
// This class filters out incoming printing related IPC messages for the // This class filters out incoming printing related IPC messages for the
// renderer process on the IPC thread. // renderer process on the IPC thread.
class PrintingMessageFilter : public content::BrowserMessageFilter { class PrintingMessageFilter : public content::BrowserMessageFilter {
public: public:
explicit PrintingMessageFilter(int render_process_id); PrintingMessageFilter(int render_process_id);
// content::BrowserMessageFilter methods. // content::BrowserMessageFilter methods.
virtual void OverrideThreadForMessage(
const IPC::Message& message,
content::BrowserThread::ID* thread) OVERRIDE;
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
private: private:
@ -49,6 +54,25 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
base::SharedMemoryHandle* browser_handle); base::SharedMemoryHandle* browser_handle);
#endif #endif
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
// Used to ask the browser allocate a temporary file for the renderer
// to fill in resulting PDF in renderer.
void OnAllocateTempFileForPrinting(int render_view_id,
base::FileDescriptor* temp_file_fd,
int* sequence_number);
void OnTempFileForPrintingWritten(int render_view_id, int sequence_number);
#endif
#if defined(OS_CHROMEOS)
void CreatePrintDialogForFile(int render_view_id, const base::FilePath& path);
#endif
#if defined(OS_ANDROID)
// Updates the file descriptor for the PrintViewManagerBasic of a given
// render_view_id.
void UpdateFileDescriptor(int render_view_id, int fd);
#endif
// Given a render_view_id get the corresponding WebContents. // Given a render_view_id get the corresponding WebContents.
// Must be called on the UI thread. // Must be called on the UI thread.
content::WebContents* GetWebContentsForRenderView(int render_view_id); content::WebContents* GetWebContentsForRenderView(int render_view_id);
@ -59,22 +83,9 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
// to base::Bind. // to base::Bind.
struct GetPrintSettingsForRenderViewParams; struct GetPrintSettingsForRenderViewParams;
// Retrieve print settings. Uses |render_view_id| to get a parent
// for any UI created if needed.
void GetPrintSettingsForRenderView(
int render_view_id,
GetPrintSettingsForRenderViewParams params,
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query);
void OnGetPrintSettingsFailed(
const base::Closure& callback,
scoped_refptr<printing::PrinterQuery> printer_query);
// Get the default print setting. // Get the default print setting.
void OnGetDefaultPrintSettings(IPC::Message* reply_msg); void OnGetDefaultPrintSettings(IPC::Message* reply_msg);
void OnGetDefaultPrintSettingsReply( void OnGetDefaultPrintSettingsReply(scoped_refptr<PrinterQuery> printer_query,
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg); IPC::Message* reply_msg);
// The renderer host have to show to the user the print dialog and returns // The renderer host have to show to the user the print dialog and returns
@ -82,15 +93,23 @@ class PrintingMessageFilter : public content::BrowserMessageFilter {
// thread and the UI thread. The reply occurs on the IO thread. // thread and the UI thread. The reply occurs on the IO thread.
void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params, void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params,
IPC::Message* reply_msg); IPC::Message* reply_msg);
void OnScriptedPrintReply( void OnScriptedPrintReply(scoped_refptr<PrinterQuery> printer_query,
scoped_refptr<printing::PrinterQuery> printer_query,
IPC::Message* reply_msg); IPC::Message* reply_msg);
#if defined(ENABLE_FULL_PRINTING)
// Check to see if print preview has been cancelled.
void OnCheckForCancel(int32 preview_ui_id,
int preview_request_id,
bool* cancel);
#endif
const int render_process_id_; const int render_process_id_;
scoped_refptr<printing::PrintQueriesQueue> queue_; scoped_refptr<PrintQueriesQueue> queue_;
DISALLOW_COPY_AND_ASSIGN(PrintingMessageFilter); DISALLOW_COPY_AND_ASSIGN(PrintingMessageFilter);
}; };
} // namespace printing
#endif // CHROME_BROWSER_PRINTING_PRINTING_MESSAGE_FILTER_H_ #endif // CHROME_BROWSER_PRINTING_PRINTING_MESSAGE_FILTER_H_

View file

@ -22,8 +22,7 @@
#include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view.h"
#include "net/base/escape.h" #include "net/base/escape.h"
#include "printing/metafile.h" #include "printing/pdf_metafile_skia.h"
#include "printing/metafile_impl.h"
#include "printing/units.h" #include "printing/units.h"
#include "skia/ext/vector_platform_device_skia.h" #include "skia/ext/vector_platform_device_skia.h"
#include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/platform/WebSize.h"
@ -65,7 +64,8 @@ bool PrintMsg_Print_Params_IsValid(const PrintMsg_Print_Params& params) {
return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() && return !params.content_size.IsEmpty() && !params.page_size.IsEmpty() &&
!params.printable_area.IsEmpty() && params.document_cookie && !params.printable_area.IsEmpty() && params.document_cookie &&
params.desired_dpi && params.max_shrink && params.min_shrink && params.desired_dpi && params.max_shrink && params.min_shrink &&
params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0); params.dpi && (params.margin_top >= 0) && (params.margin_left >= 0) &&
params.dpi > kMinDpi && params.document_cookie != 0;
} }
PrintMsg_Print_Params GetCssPrintParams( PrintMsg_Print_Params GetCssPrintParams(
@ -409,8 +409,6 @@ class PrepareFrameAndViewForPrint : public blink::WebViewClient,
return expected_pages_count_; return expected_pages_count_;
} }
gfx::Size GetPrintCanvasSize() const;
void FinishPrinting(); void FinishPrinting();
bool IsLoadingSelection() { bool IsLoadingSelection() {
@ -590,12 +588,6 @@ void PrepareFrameAndViewForPrint::CallOnReady() {
return on_ready_.Run(); // Can delete |this|. return on_ready_.Run(); // Can delete |this|.
} }
gfx::Size PrepareFrameAndViewForPrint::GetPrintCanvasSize() const {
DCHECK(is_printing_started_);
return gfx::Size(web_print_params_.printContentArea.width,
web_print_params_.printContentArea.height);
}
void PrepareFrameAndViewForPrint::RestoreSize() { void PrepareFrameAndViewForPrint::RestoreSize() {
if (frame()) { if (frame()) {
blink::WebView* web_view = frame_.GetFrame()->view(); blink::WebView* web_view = frame_.GetFrame()->view();
@ -606,7 +598,7 @@ void PrepareFrameAndViewForPrint::RestoreSize() {
} }
void PrepareFrameAndViewForPrint::FinishPrinting() { void PrepareFrameAndViewForPrint::FinishPrinting() {
blink::WebFrame* frame = frame_.GetFrame(); blink::WebLocalFrame* frame = frame_.GetFrame();
if (frame) { if (frame) {
blink::WebView* web_view = frame->view(); blink::WebView* web_view = frame->view();
if (is_printing_started_) { if (is_printing_started_) {
@ -630,10 +622,15 @@ void PrepareFrameAndViewForPrint::FinishPrinting() {
PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view) PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
: content::RenderViewObserver(render_view), : content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view), content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
reset_prep_frame_view_(false),
is_print_ready_metafile_sent_(false), is_print_ready_metafile_sent_(false),
ignore_css_margins_(false), ignore_css_margins_(false),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true), notify_browser_of_print_failure_(true),
print_for_preview_(false),
print_node_in_progress_(false), print_node_in_progress_(false),
is_loading_(false),
is_scripted_preview_delayed_(false),
weak_ptr_factory_(this) { weak_ptr_factory_(this) {
} }
@ -673,11 +670,13 @@ bool PrintWebViewHelper::GetPrintFrame(blink::WebLocalFrame** frame) {
return true; return true;
} }
#if !defined(DISABLE_BASIC_PRINTING)
void PrintWebViewHelper::OnPrintPages(bool silent, bool print_background) { void PrintWebViewHelper::OnPrintPages(bool silent, bool print_background) {
blink::WebLocalFrame* frame; blink::WebLocalFrame* frame;
if (GetPrintFrame(&frame)) if (GetPrintFrame(&frame))
Print(frame, blink::WebNode(), silent, print_background); Print(frame, blink::WebNode(), silent, print_background);
} }
#endif // !DISABLE_BASIC_PRINTING
void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout( void PrintWebViewHelper::GetPageSizeAndContentAreaFromPageLayout(
const PageSizeMargins& page_layout_in_points, const PageSizeMargins& page_layout_in_points,
@ -726,9 +725,6 @@ void PrintWebViewHelper::PrintNode(const blink::WebNode& node) {
} }
print_node_in_progress_ = true; print_node_in_progress_ = true;
// Make a copy of the node, in case RenderView::OnContextMenuClosed resets
// its |context_menu_node_|.
blink::WebNode duplicate_node(node); blink::WebNode duplicate_node(node);
Print(duplicate_node.document().frame(), duplicate_node); Print(duplicate_node.document().frame(), duplicate_node);
@ -783,7 +779,7 @@ void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) {
break; break;
case FAIL_PRINT: case FAIL_PRINT:
if (notify_browser_of_print_failure_ && print_pages_params_.get()) { if (notify_browser_of_print_failure_ && print_pages_params_) {
int cookie = print_pages_params_->params.document_cookie; int cookie = print_pages_params_->params.document_cookie;
Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie)); Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie));
} }
@ -821,8 +817,7 @@ void PrintWebViewHelper::PrintPages() {
page_count)); page_count));
#endif // !defined(OS_CHROMEOS) #endif // !defined(OS_CHROMEOS)
if (!PrintPagesNative(prep_frame_view_->frame(), page_count, if (!PrintPagesNative(prep_frame_view_->frame(), page_count)) {
prep_frame_view_->GetPrintCanvasSize())) {
LOG(ERROR) << "Printing failed."; LOG(ERROR) << "Printing failed.";
return DidFinishPrinting(FAIL_PRINT); return DidFinishPrinting(FAIL_PRINT);
} }
@ -832,10 +827,9 @@ void PrintWebViewHelper::FinishFramePrinting() {
prep_frame_view_.reset(); prep_frame_view_.reset();
} }
#if defined(OS_MACOSX) || defined(OS_WIN) #if defined(OS_MACOSX)
bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
int page_count, int page_count) {
const gfx::Size& canvas_size) {
const PrintMsg_PrintPages_Params& params = *print_pages_params_; const PrintMsg_PrintPages_Params& params = *print_pages_params_;
const PrintMsg_Print_Params& print_params = params.params; const PrintMsg_Print_Params& print_params = params.params;
@ -844,20 +838,20 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
if (params.pages.empty()) { if (params.pages.empty()) {
for (int i = 0; i < page_count; ++i) { for (int i = 0; i < page_count; ++i) {
page_params.page_number = i; page_params.page_number = i;
PrintPageInternal(page_params, canvas_size, frame); PrintPageInternal(page_params, frame);
} }
} else { } else {
for (size_t i = 0; i < params.pages.size(); ++i) { for (size_t i = 0; i < params.pages.size(); ++i) {
if (params.pages[i] >= page_count) if (params.pages[i] >= page_count)
break; break;
page_params.page_number = params.pages[i]; page_params.page_number = params.pages[i];
PrintPageInternal(page_params, canvas_size, frame); PrintPageInternal(page_params, frame);
} }
} }
return true; return true;
} }
#endif // OS_MACOSX || OS_WIN #endif // OS_MACOSX
// static - Not anonymous so that platform implementations can use it. // static - Not anonymous so that platform implementations can use it.
void PrintWebViewHelper::ComputePageLayoutInPointsForCss( void PrintWebViewHelper::ComputePageLayoutInPointsForCss(
@ -886,13 +880,6 @@ bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
if (!PrintMsg_Print_Params_IsValid(settings.params)) if (!PrintMsg_Print_Params_IsValid(settings.params))
result = false; result = false;
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
// Invalid print page settings.
NOTREACHED();
result = false;
}
// Reset to default values. // Reset to default values.
ignore_css_margins_ = false; ignore_css_margins_ = false;
settings.pages.clear(); settings.pages.clear();
@ -904,7 +891,7 @@ bool PrintWebViewHelper::InitPrintSettings(bool fit_to_paper_size) {
blink::WebPrintScalingOptionFitToPrintableArea; blink::WebPrintScalingOptionFitToPrintableArea;
} }
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); SetPrintPagesParams(settings);
return result; return result;
} }
@ -923,8 +910,6 @@ bool PrintWebViewHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame,
PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_); PrepareFrameAndViewForPrint prepare(params, frame, node, ignore_css_margins_);
prepare.StartPrinting(); prepare.StartPrinting();
Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(),
params.document_cookie));
*number_of_pages = prepare.GetExpectedPageCount(); *number_of_pages = prepare.GetExpectedPageCount();
return true; return true;
} }
@ -953,9 +938,8 @@ bool PrintWebViewHelper::GetPrintSettingsFromUser(blink::WebFrame* frame,
new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings); new PrintHostMsg_ScriptedPrint(routing_id(), params, &print_settings);
msg->EnableMessagePumping(); msg->EnableMessagePumping();
Send(msg); Send(msg);
print_pages_params_.reset(new PrintMsg_PrintPages_Params(print_settings)); print_settings.params.print_scaling_option = scaling_option;
SetPrintPagesParams(print_settings);
print_pages_params_->params.print_scaling_option = scaling_option;
return (print_settings.params.dpi && print_settings.params.document_cookie); return (print_settings.params.dpi && print_settings.params.document_cookie);
} }
@ -965,9 +949,8 @@ bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
return false; return false;
const PrintMsg_PrintPages_Params& params = *print_pages_params_; const PrintMsg_PrintPages_Params& params = *print_pages_params_;
const PrintMsg_Print_Params& print_params = params.params; const PrintMsg_Print_Params& print_params = params.params;
prep_frame_view_.reset( prep_frame_view_.reset(new PrepareFrameAndViewForPrint(
new PrepareFrameAndViewForPrint(print_params, frame, node, print_params, frame, node, ignore_css_margins_));
ignore_css_margins_));
DCHECK(!print_pages_params_->params.selection_only || DCHECK(!print_pages_params_->params.selection_only ||
print_pages_params_->pages.empty()); print_pages_params_->pages.empty());
prep_frame_view_->CopySelectionIfNeeded( prep_frame_view_->CopySelectionIfNeeded(
@ -979,24 +962,27 @@ bool PrintWebViewHelper::RenderPagesForPrint(blink::WebLocalFrame* frame,
#if defined(OS_POSIX) #if defined(OS_POSIX)
bool PrintWebViewHelper::CopyMetafileDataToSharedMem( bool PrintWebViewHelper::CopyMetafileDataToSharedMem(
Metafile* metafile, PdfMetafileSkia* metafile,
base::SharedMemoryHandle* shared_mem_handle) { base::SharedMemoryHandle* shared_mem_handle) {
uint32 buf_size = metafile->GetDataSize(); uint32 buf_size = metafile->GetDataSize();
scoped_ptr<base::SharedMemory> shared_buf( scoped_ptr<base::SharedMemory> shared_buf(
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer( content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(
buf_size).release()); buf_size).release());
if (shared_buf.get()) { if (shared_buf) {
if (shared_buf->Map(buf_size)) { if (shared_buf->Map(buf_size)) {
metafile->GetData(shared_buf->memory(), buf_size); metafile->GetData(shared_buf->memory(), buf_size);
shared_buf->GiveToProcess(base::GetCurrentProcessHandle(), return shared_buf->GiveToProcess(base::GetCurrentProcessHandle(),
shared_mem_handle); shared_mem_handle);
return true;
} }
} }
NOTREACHED();
return false; return false;
} }
#endif // defined(OS_POSIX) #endif // defined(OS_POSIX)
void PrintWebViewHelper::SetPrintPagesParams(
const PrintMsg_PrintPages_Params& settings) {
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
}
} // namespace printing } // namespace printing

View file

@ -7,13 +7,15 @@
#include <vector> #include <vector>
#include "base/callback.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/shared_memory.h" #include "base/memory/shared_memory.h"
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/time/time.h" #include "base/time/time.h"
#include "content/public/renderer/render_view_observer.h" #include "content/public/renderer/render_view_observer.h"
#include "content/public/renderer/render_view_observer_tracker.h" #include "content/public/renderer/render_view_observer_tracker.h"
#include "printing/metafile_impl.h" #include "printing/pdf_metafile_skia.h"
#include "third_party/WebKit/public/platform/WebCanvas.h" #include "third_party/WebKit/public/platform/WebCanvas.h"
#include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebNode.h"
#include "third_party/WebKit/public/web/WebPrintParams.h" #include "third_party/WebKit/public/web/WebPrintParams.h"
@ -22,6 +24,7 @@
struct PrintMsg_Print_Params; struct PrintMsg_Print_Params;
struct PrintMsg_PrintPage_Params; struct PrintMsg_PrintPage_Params;
struct PrintMsg_PrintPages_Params; struct PrintMsg_PrintPages_Params;
struct PrintHostMsg_SetOptionsFromDocument_Params;
namespace base { namespace base {
class DictionaryValue; class DictionaryValue;
@ -81,8 +84,10 @@ class PrintWebViewHelper
bool user_initiated) OVERRIDE; bool user_initiated) OVERRIDE;
// Message handlers --------------------------------------------------------- // Message handlers ---------------------------------------------------------
#if !defined(DISABLE_BASIC_PRINTING)
void OnPrintPages(bool silent, bool print_background); void OnPrintPages(bool silent, bool print_background);
void OnPrintingDone(bool success); void OnPrintingDone(bool success);
#endif // !DISABLE_BASIC_PRINTING
// Get |page_size| and |content_area| information from // Get |page_size| and |content_area| information from
// |page_layout_in_points|. // |page_layout_in_points|.
@ -125,20 +130,22 @@ class PrintWebViewHelper
void OnFramePreparedForPrintPages(); void OnFramePreparedForPrintPages();
void PrintPages(); void PrintPages();
bool PrintPagesNative(blink::WebFrame* frame, bool PrintPagesNative(blink::WebFrame* frame, int page_count);
int page_count,
const gfx::Size& canvas_size);
void FinishFramePrinting(); void FinishFramePrinting();
// Prints the page listed in |params|. // Prints the page listed in |params|.
#if defined(OS_LINUX) || defined(OS_ANDROID) #if defined(OS_LINUX) || defined(OS_ANDROID)
void PrintPageInternal(const PrintMsg_PrintPage_Params& params, void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
const gfx::Size& canvas_size,
blink::WebFrame* frame, blink::WebFrame* frame,
Metafile* metafile); PdfMetafileSkia* metafile);
#elif defined(OS_WIN)
void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
blink::WebFrame* frame,
PdfMetafileSkia* metafile,
gfx::Size* page_size_in_dpi,
gfx::Rect* content_area_in_dpi);
#else #else
void PrintPageInternal(const PrintMsg_PrintPage_Params& params, void PrintPageInternal(const PrintMsg_PrintPage_Params& params,
const gfx::Size& canvas_size,
blink::WebFrame* frame); blink::WebFrame* frame);
#endif #endif
@ -147,24 +154,15 @@ class PrintWebViewHelper
const blink::WebNode& node); const blink::WebNode& node);
// Platform specific helper function for rendering page(s) to |metafile|. // Platform specific helper function for rendering page(s) to |metafile|.
#if defined(OS_WIN) #if defined(OS_MACOSX)
void RenderPage(const PrintMsg_Print_Params& params, void RenderPage(const PrintMsg_Print_Params& params,
int page_number, int page_number,
blink::WebFrame* frame, blink::WebFrame* frame,
bool is_preview, bool is_preview,
Metafile* metafile, PdfMetafileSkia* metafile,
double* scale_factor,
gfx::Size* page_size_in_dpi,
gfx::Rect* content_area_in_dpi);
#elif defined(OS_MACOSX)
void RenderPage(const PrintMsg_Print_Params& params,
int page_number,
blink::WebFrame* frame,
bool is_preview,
Metafile* metafile,
gfx::Size* page_size, gfx::Size* page_size,
gfx::Rect* content_rect); gfx::Rect* content_rect);
#endif // defined(OS_WIN) #endif // defined(OS_MACOSX)
// Renders page contents from |frame| to |content_area| of |canvas|. // Renders page contents from |frame| to |content_area| of |canvas|.
// |page_number| is zero-based. // |page_number| is zero-based.
@ -179,7 +177,7 @@ class PrintWebViewHelper
// Helper methods ----------------------------------------------------------- // Helper methods -----------------------------------------------------------
bool CopyMetafileDataToSharedMem(Metafile* metafile, bool CopyMetafileDataToSharedMem(PdfMetafileSkia* metafile,
base::SharedMemoryHandle* shared_mem_handle); base::SharedMemoryHandle* shared_mem_handle);
// Helper method to get page layout in points and fit to page if needed. // Helper method to get page layout in points and fit to page if needed.
@ -195,18 +193,35 @@ class PrintWebViewHelper
// Script Initiated Printing ------------------------------------------------ // Script Initiated Printing ------------------------------------------------
void SetPrintPagesParams(const PrintMsg_PrintPages_Params& settings);
// WebView used only to print the selection. // WebView used only to print the selection.
scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_; scoped_ptr<PrepareFrameAndViewForPrint> prep_frame_view_;
bool reset_prep_frame_view_;
scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_; scoped_ptr<PrintMsg_PrintPages_Params> print_pages_params_;
bool is_print_ready_metafile_sent_; bool is_print_ready_metafile_sent_;
bool ignore_css_margins_; bool ignore_css_margins_;
// Used for scripted initiated printing blocking.
bool is_scripted_printing_blocked_;
// Let the browser process know of a printing failure. Only set to false when // Let the browser process know of a printing failure. Only set to false when
// the failure came from the browser in the first place. // the failure came from the browser in the first place.
bool notify_browser_of_print_failure_; bool notify_browser_of_print_failure_;
// True, when printing from print preview.
bool print_for_preview_;
bool print_node_in_progress_; bool print_node_in_progress_;
bool is_loading_;
bool is_scripted_preview_delayed_;
// Used to fix a race condition where the source is a PDF and print preview
// hangs because RequestPrintPreview is called before DidStopLoading() is
// called. This is a store for the RequestPrintPreview() call and its
// parameters so that it can be invoked after DidStopLoading.
base::Closure on_stop_loading_closure_;
base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_; base::WeakPtrFactory<PrintWebViewHelper> weak_ptr_factory_;

View file

@ -8,10 +8,9 @@
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "chrome/common/print_messages.h" #include "chrome/common/print_messages.h"
#include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_thread.h"
#include "printing/metafile.h"
#include "printing/metafile_impl.h"
#include "printing/metafile_skia_wrapper.h" #include "printing/metafile_skia_wrapper.h"
#include "printing/page_size_margins.h" #include "printing/page_size_margins.h"
#include "printing/pdf_metafile_skia.h"
#include "skia/ext/platform_device.h" #include "skia/ext/platform_device.h"
#include "skia/ext/vector_canvas.h" #include "skia/ext/vector_canvas.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h"
@ -27,9 +26,8 @@ namespace printing {
using blink::WebFrame; using blink::WebFrame;
bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame, bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
int page_count, int page_count) {
const gfx::Size& canvas_size) { PdfMetafileSkia metafile;
NativeMetafile metafile;
if (!metafile.Init()) if (!metafile.Init())
return false; return false;
@ -56,7 +54,7 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
page_params.params = params.params; page_params.params = params.params;
for (size_t i = 0; i < printed_pages.size(); ++i) { for (size_t i = 0; i < printed_pages.size(); ++i) {
page_params.page_number = printed_pages[i]; page_params.page_number = printed_pages[i];
PrintPageInternal(page_params, canvas_size, frame, &metafile); PrintPageInternal(page_params, frame, &metafile);
} }
// blink::printEnd() for PDF should be called before metafile is closed. // blink::printEnd() for PDF should be called before metafile is closed.
@ -119,9 +117,8 @@ bool PrintWebViewHelper::PrintPagesNative(blink::WebFrame* frame,
void PrintWebViewHelper::PrintPageInternal( void PrintWebViewHelper::PrintPageInternal(
const PrintMsg_PrintPage_Params& params, const PrintMsg_PrintPage_Params& params,
const gfx::Size& canvas_size,
WebFrame* frame, WebFrame* frame,
Metafile* metafile) { PdfMetafileSkia* metafile) {
PageSizeMargins page_layout_in_points; PageSizeMargins page_layout_in_points;
double scale_factor = 1.0f; double scale_factor = 1.0f;
ComputePageLayoutInPointsForCss(frame, params.page_number, params.params, ComputePageLayoutInPointsForCss(frame, params.page_number, params.params,

View file

@ -10,8 +10,6 @@
#include "base/mac/scoped_nsautorelease_pool.h" #include "base/mac/scoped_nsautorelease_pool.h"
#include "base/metrics/histogram.h" #include "base/metrics/histogram.h"
#include "chrome/common/print_messages.h" #include "chrome/common/print_messages.h"
#include "printing/metafile.h"
#include "printing/metafile_impl.h"
#include "printing/metafile_skia_wrapper.h" #include "printing/metafile_skia_wrapper.h"
#include "printing/page_size_margins.h" #include "printing/page_size_margins.h"
#include "skia/ext/platform_device.h" #include "skia/ext/platform_device.h"
@ -25,9 +23,8 @@ using blink::WebFrame;
void PrintWebViewHelper::PrintPageInternal( void PrintWebViewHelper::PrintPageInternal(
const PrintMsg_PrintPage_Params& params, const PrintMsg_PrintPage_Params& params,
const gfx::Size& canvas_size,
WebFrame* frame) { WebFrame* frame) {
NativeMetafile metafile; PdfMetafileSkia metafile;
if (!metafile.Init()) if (!metafile.Init())
return; return;
@ -54,9 +51,12 @@ void PrintWebViewHelper::PrintPageInternal(
Send(new PrintHostMsg_DidPrintPage(routing_id(), page_params)); Send(new PrintHostMsg_DidPrintPage(routing_id(), page_params));
} }
void PrintWebViewHelper::RenderPage( void PrintWebViewHelper::RenderPage(const PrintMsg_Print_Params& params,
const PrintMsg_Print_Params& params, int page_number, WebFrame* frame, int page_number,
bool is_preview, Metafile* metafile, gfx::Size* page_size, WebFrame* frame,
bool is_preview,
PdfMetafileSkia* metafile,
gfx::Size* page_size,
gfx::Rect* content_rect) { gfx::Rect* content_rect) {
double scale_factor = 1.0f; double scale_factor = 1.0f;
double webkit_shrink_factor = frame->getPrintPageShrink(page_number); double webkit_shrink_factor = frame->getPrintPageShrink(page_number);

2
vendor/brightray vendored

@ -1 +1 @@
Subproject commit 4f04cc8121dd05ed61a8c94edfa66201e12f0abb Subproject commit f7f439bdd31c901c802108ec903a3bfc0448c3d1