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

Side by Side Diff: chrome/browser/printing/pdf_to_emf_converter.cc

Issue 566693002: Use file handles to interact with utility process. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Tue Sep 16 01:11:23 PDT 2014 Created 6 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « chrome/browser/printing/pdf_to_emf_converter.h ('k') | chrome/browser/printing/print_job.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/printing/pdf_to_emf_converter.h" 5 #include "chrome/browser/printing/pdf_to_emf_converter.h"
6 6
7 #include "base/bind_helpers.h" 7 #include <queue>
8 #include "base/cancelable_callback.h" 8
9 #include "base/files/file.h" 9 #include "base/files/file.h"
10 #include "base/files/file_util.h" 10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h" 11 #include "base/files/scoped_temp_dir.h"
12 #include "base/lazy_instance.h"
12 #include "base/logging.h" 13 #include "base/logging.h"
13 #include "chrome/common/chrome_utility_messages.h" 14 #include "chrome/common/chrome_utility_messages.h"
14 #include "chrome/common/chrome_utility_printing_messages.h" 15 #include "chrome/common/chrome_utility_printing_messages.h"
15 #include "content/public/browser/browser_thread.h" 16 #include "content/public/browser/browser_thread.h"
16 #include "content/public/browser/child_process_data.h" 17 #include "content/public/browser/child_process_data.h"
17 #include "content/public/browser/utility_process_host.h" 18 #include "content/public/browser/utility_process_host.h"
18 #include "content/public/browser/utility_process_host_client.h" 19 #include "content/public/browser/utility_process_host_client.h"
19 #include "printing/emf_win.h" 20 #include "printing/emf_win.h"
20 #include "printing/page_range.h"
21 #include "printing/pdf_render_settings.h" 21 #include "printing/pdf_render_settings.h"
22 22
23 namespace printing { 23 namespace printing {
24 24
25 namespace { 25 namespace {
26 26
27 using content::BrowserThread; 27 using content::BrowserThread;
28 28
29 class FileHandlers 29 class PdfToEmfConverterImpl;
30 : public base::RefCountedThreadSafe<FileHandlers, 30
31 BrowserThread::DeleteOnFileThread> { 31 typedef scoped_ptr<base::File, BrowserThread::DeleteOnFileThread>
32 ScopedTempFile;
33
34 // Wrapper for Emf to keep only file handle in memory, and load actual data only
35 // on playback. Emf::InitFromFile() can play metafile directly from disk, but it
36 // can't open file handles. We need file handles to reliably delete temporary
37 // files, and to efficiently interact with utility process.
38 class LazyEmf : public MetafilePlayer {
32 public: 39 public:
33 FileHandlers() {} 40 explicit LazyEmf(ScopedTempFile file) : file_(file.Pass()) {}
34 41 virtual ~LazyEmf() { Close(); }
35 void Init(base::RefCountedMemory* data); 42
36 bool IsValid(); 43 virtual bool SafePlayback(HDC hdc) const OVERRIDE;
37 44 virtual bool SaveTo(base::File* file) const OVERRIDE;
38 base::FilePath GetEmfPath() const {
39 return temp_dir_.path().AppendASCII("output.emf");
40 }
41
42 base::FilePath GetEmfPagePath(int page_number) const {
43 return GetEmfPath().InsertBeforeExtensionASCII(
44 base::StringPrintf(".%d", page_number));
45 }
46
47 base::FilePath GetPdfPath() const {
48 return temp_dir_.path().AppendASCII("input.pdf");
49 }
50
51 IPC::PlatformFileForTransit GetPdfForProcess(base::ProcessHandle process) {
52 DCHECK(pdf_file_.IsValid());
53 IPC::PlatformFileForTransit transit =
54 IPC::TakeFileHandleForProcess(pdf_file_.Pass(), process);
55 return transit;
56 }
57
58 const base::FilePath& GetBasePath() const {
59 return temp_dir_.path();
60 }
61 45
62 private: 46 private:
63 friend struct BrowserThread::DeleteOnThread<BrowserThread::FILE>; 47 void Close() const;
64 friend class base::DeleteHelper<FileHandlers>; 48 bool LoadEmf(Emf* emf) const;
65 49
66 ~FileHandlers() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); } 50 mutable ScopedTempFile file_; // Mutable because of consts in base class.
67 51 DISALLOW_COPY_AND_ASSIGN(LazyEmf);
68 base::ScopedTempDir temp_dir_;
69 base::File pdf_file_;
70 };
71
72 void FileHandlers::Init(base::RefCountedMemory* data) {
73 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
74
75 if (!temp_dir_.CreateUniqueTempDir()) {
76 return;
77 }
78
79 pdf_file_.Initialize(GetPdfPath(),
80 base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE |
81 base::File::FLAG_READ |
82 base::File::FLAG_DELETE_ON_CLOSE);
83 if (static_cast<int>(data->size()) !=
84 pdf_file_.WriteAtCurrentPos(data->front_as<char>(), data->size())) {
85 pdf_file_.Close();
86 return;
87 }
88 pdf_file_.Seek(base::File::FROM_BEGIN, 0);
89 pdf_file_.Flush();
90 }
91
92 bool FileHandlers::IsValid() {
93 return pdf_file_.IsValid();
94 }
95
96 // Modification of Emf to keep references to |FileHandlers|.
97 // |FileHandlers| must be deleted after the last metafile is closed because
98 // Emf holds files locked.
99 // Ideally we want to use FLAG_DELETE_ON_CLOSE, but it requires large changes.
100 // It's going to be done for crbug.com/408184
101 class TempEmf : public Emf {
102 public:
103 explicit TempEmf(const scoped_refptr<FileHandlers>& files) : files_(files) {}
104 virtual ~TempEmf() {}
105
106 virtual bool SafePlayback(HDC hdc) const OVERRIDE {
107 bool result = Emf::SafePlayback(hdc);
108 TempEmf* this_mutable = const_cast<TempEmf*>(this);
109 // TODO(vitalybuka): Fix destruction of metafiles. For some reasons
110 // instances of Emf are not deleted. crbug.com/411683
111 // |files_| must be released as soon as possible to guarantee deletion.
112 // It's know that this Emf file is going to be played just once to
113 // a printer. So just release files here.
114 this_mutable->Close();
115 this_mutable->files_ = NULL;
116 return result;
117 }
118
119 private:
120 scoped_refptr<FileHandlers> files_;
121 DISALLOW_COPY_AND_ASSIGN(TempEmf);
122 }; 52 };
123 53
124 // Converts PDF into EMF. 54 // Converts PDF into EMF.
125 // Class uses 3 threads: UI, IO and FILE. 55 // Class uses 3 threads: UI, IO and FILE.
126 // Internal workflow is following: 56 // Internal workflow is following:
127 // 1. Create instance on the UI thread. (files_, settings_,) 57 // 1. Create instance on the UI thread. (files_, settings_,)
128 // 2. Create file on the FILE thread. 58 // 2. Create pdf file on the FILE thread.
129 // 3. Start utility process and start conversion on the IO thread. 59 // 3. Start utility process and start conversion on the IO thread.
130 // 4. Run result callback on the UI thread. 60 // 4. Utility process returns page count.
131 // 5. Instance is destroyed from any thread that has the last reference. 61 // 5. For each page:
132 // 6. FileHandlers destroyed on the FILE thread. 62 // 1. Clients requests page with file handle to a temp file.
133 // This step posts |FileHandlers| to be destroyed on the FILE thread. 63 // 2. Utility converts the page, save it to the file and reply.
64 //
134 // All these steps work sequentially, so no data should be accessed 65 // All these steps work sequentially, so no data should be accessed
135 // simultaneously by several threads. 66 // simultaneously by several threads.
136 class PdfToEmfUtilityProcessHostClient 67 class PdfToEmfUtilityProcessHostClient
137 : public content::UtilityProcessHostClient { 68 : public content::UtilityProcessHostClient {
138 public: 69 public:
139 explicit PdfToEmfUtilityProcessHostClient( 70 PdfToEmfUtilityProcessHostClient(
140 const printing::PdfRenderSettings& settings); 71 base::WeakPtr<PdfToEmfConverterImpl> converter,
141 72 const PdfRenderSettings& settings);
142 void Convert(base::RefCountedMemory* data, 73
143 const PdfToEmfConverter::ResultCallback& callback); 74 void Start(const scoped_refptr<base::RefCountedMemory>& data,
75 const PdfToEmfConverter::StartCallback& start_callback);
76
77 void GetPage(int page_number,
78 const PdfToEmfConverter::GetPageCallback& get_page_callback);
79
80 void Stop();
144 81
145 // UtilityProcessHostClient implementation. 82 // UtilityProcessHostClient implementation.
146 virtual void OnProcessCrashed(int exit_code) OVERRIDE; 83 virtual void OnProcessCrashed(int exit_code) OVERRIDE;
84 virtual void OnProcessLaunchFailed() OVERRIDE;
147 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; 85 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
148 86
149 private: 87 private:
88 class GetPageCallbackData {
89 MOVE_ONLY_TYPE_FOR_CPP_03(GetPageCallbackData, RValue);
90
91 public:
92 GetPageCallbackData(int page_number,
93 PdfToEmfConverter::GetPageCallback callback)
94 : page_number_(page_number), callback_(callback) {}
95
96 // Move constructor for STL.
97 GetPageCallbackData(RValue other) { this->operator=(other); }
98
99 // Move assignment for STL.
100 GetPageCallbackData& operator=(RValue rhs) {
101 page_number_ = rhs.object->page_number_;
102 callback_ = rhs.object->callback_;
103 emf_ = rhs.object->emf_.Pass();
104 return *this;
105 }
106
107 int page_number() const { return page_number_; }
108 const PdfToEmfConverter::GetPageCallback& callback() const {
109 return callback_;
110 }
111 ScopedTempFile emf() { return emf_.Pass(); }
112 void set_emf(ScopedTempFile emf) { emf_ = emf.Pass(); }
113
114 private:
115 int page_number_;
116 PdfToEmfConverter::GetPageCallback callback_;
117 ScopedTempFile emf_;
118 };
119
150 virtual ~PdfToEmfUtilityProcessHostClient(); 120 virtual ~PdfToEmfUtilityProcessHostClient();
151 121
122 bool Send(IPC::Message* msg);
123
152 // Message handlers. 124 // Message handlers.
153 void OnProcessStarted(); 125 void OnProcessStarted();
154 void OnSucceeded(const std::vector<printing::PageRange>& page_ranges, 126 void OnPageCount(int page_count);
155 double scale_factor); 127 void OnPageDone(bool success, double scale_factor);
128
156 void OnFailed(); 129 void OnFailed();
157 130 void OnTempPdfReady(ScopedTempFile pdf);
158 void RunCallback(const std::vector<printing::PageRange>& page_ranges, 131 void OnTempEmfReady(GetPageCallbackData* callback_data, ScopedTempFile emf);
159 double scale_factor); 132
160 133 // Used to suppress callbacks after PdfToEmfConverterImpl is deleted.
161 void StartProcessOnIOThread(); 134 base::WeakPtr<PdfToEmfConverterImpl> converter_;
162 135 PdfRenderSettings settings_;
163 void RunCallbackOnUIThread( 136 scoped_refptr<base::RefCountedMemory> data_;
164 const std::vector<printing::PageRange>& page_ranges, 137
165 double scale_factor); 138 // Document loaded callback.
166 void OnFilesReadyOnUIThread(); 139 PdfToEmfConverter::StartCallback start_callback_;
167 140
168 scoped_refptr<FileHandlers> files_; 141 // Process host for IPC.
169 printing::PdfRenderSettings settings_;
170 PdfToEmfConverter::ResultCallback callback_;
171 base::WeakPtr<content::UtilityProcessHost> utility_process_host_; 142 base::WeakPtr<content::UtilityProcessHost> utility_process_host_;
172 143
144 // Queue of callbacks for GetPage() requests. Utility process should reply
145 // with PageDone in the same order as requests were received.
146 // Use containers that keeps element pointers valid after push() and pop().
147 typedef std::queue<GetPageCallbackData> GetPageCallbacks;
148 GetPageCallbacks get_page_callbacks_;
149
173 DISALLOW_COPY_AND_ASSIGN(PdfToEmfUtilityProcessHostClient); 150 DISALLOW_COPY_AND_ASSIGN(PdfToEmfUtilityProcessHostClient);
174 }; 151 };
175 152
153 class PdfToEmfConverterImpl : public PdfToEmfConverter {
154 public:
155 PdfToEmfConverterImpl();
156
157 virtual ~PdfToEmfConverterImpl();
158
159 virtual void Start(const scoped_refptr<base::RefCountedMemory>& data,
160 const PdfRenderSettings& conversion_settings,
161 const StartCallback& start_callback) OVERRIDE;
162
163 virtual void GetPage(int page_number,
164 const GetPageCallback& get_page_callback) OVERRIDE;
165
166 // Helps to cancel callbacks if this object is destroyed.
167 void RunCallback(const base::Closure& callback);
168
169 private:
170 scoped_refptr<PdfToEmfUtilityProcessHostClient> utility_client_;
171 base::WeakPtrFactory<PdfToEmfConverterImpl> weak_ptr_factory_;
172
173 DISALLOW_COPY_AND_ASSIGN(PdfToEmfConverterImpl);
174 };
175
176 // Use global object to avoid tracking all opened files.
Lei Zhang 2014/09/16 19:57:36 I'm slightly confused by this comment. Aren't you
Vitaly Buka (NO REVIEWS) 2014/09/16 22:10:37 I don't want global TEMP dir, to avoid polluted di
Lei Zhang 2014/09/16 22:39:59 Oh, is the problem that ScopedTempDir doesn't work
177 base::LazyInstance<base::ScopedTempDir> g_temp_dir = LAZY_INSTANCE_INITIALIZER;
178
179 ScopedTempFile CreateTempFile() {
180 base::ScopedTempDir& temp_dir = g_temp_dir.Get();
181 ScopedTempFile file;
182 if (!temp_dir.IsValid() && !temp_dir.CreateUniqueTempDir())
183 return file.Pass();
184 base::FilePath path;
185 if (!base::CreateTemporaryFileInDir(temp_dir.path(), &path))
186 return file.Pass();
187 file.reset(new base::File(path,
188 base::File::FLAG_CREATE_ALWAYS |
189 base::File::FLAG_WRITE | base::File::FLAG_READ |
190 base::File::FLAG_DELETE_ON_CLOSE |
191 base::File::FLAG_TEMPORARY));
192 if (!file->IsValid())
193 file.reset();
194 return file.Pass();
195 }
196
197 ScopedTempFile CreateTempPdfFile(
198 const scoped_refptr<base::RefCountedMemory>& data) {
199 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
200
201 ScopedTempFile pdf_file = CreateTempFile();
202 if (!pdf_file ||
203 static_cast<int>(data->size()) !=
204 pdf_file->WriteAtCurrentPos(data->front_as<char>(), data->size())) {
205 pdf_file.reset();
206 }
207 pdf_file->Seek(base::File::FROM_BEGIN, 0);
208 return pdf_file.Pass();
209 }
210
211 bool LazyEmf::SafePlayback(HDC hdc) const {
212 Emf emf;
213 bool result = LoadEmf(&emf) && emf.SafePlayback(hdc);
214 // TODO(vitalybuka): Fix destruction of metafiles. For some reasons
215 // instances of Emf are not deleted. crbug.com/411683
216 // It's known that the Emf going to be played just once to a printer. So just
217 // release file here.
218 Close();
219 return result;
220 }
221
222 bool LazyEmf::SaveTo(base::File* file) const {
223 Emf emf;
224 return LoadEmf(&emf) && emf.SaveTo(file);
225 }
226
227 void LazyEmf::Close() const {
228 file_.reset();
229 }
230
231 bool LazyEmf::LoadEmf(Emf* emf) const {
232 file_->Seek(base::File::FROM_BEGIN, 0);
233 int64 size = file_->GetLength();
234 if (size <= 0)
235 return false;
236 std::vector<char> data(size);
237 if (file_->ReadAtCurrentPos(data.data(), data.size()) != size)
238 return false;
239 return emf->InitFromData(data.data(), data.size());
240 }
241
176 PdfToEmfUtilityProcessHostClient::PdfToEmfUtilityProcessHostClient( 242 PdfToEmfUtilityProcessHostClient::PdfToEmfUtilityProcessHostClient(
177 const printing::PdfRenderSettings& settings) 243 base::WeakPtr<PdfToEmfConverterImpl> converter,
178 : settings_(settings) {} 244 const PdfRenderSettings& settings)
245 : converter_(converter), settings_(settings) {
246 }
179 247
180 PdfToEmfUtilityProcessHostClient::~PdfToEmfUtilityProcessHostClient() { 248 PdfToEmfUtilityProcessHostClient::~PdfToEmfUtilityProcessHostClient() {
181 } 249 }
182 250
183 void PdfToEmfUtilityProcessHostClient::Convert( 251 void PdfToEmfUtilityProcessHostClient::Start(
184 base::RefCountedMemory* data, 252 const scoped_refptr<base::RefCountedMemory>& data,
185 const PdfToEmfConverter::ResultCallback& callback) { 253 const PdfToEmfConverter::StartCallback& start_callback) {
186 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 254 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
187 callback_ = callback; 255 BrowserThread::PostTask(BrowserThread::IO,
188 CHECK(!files_.get()); 256 FROM_HERE,
189 files_ = new FileHandlers(); 257 base::Bind(&PdfToEmfUtilityProcessHostClient::Start,
190 BrowserThread::PostTaskAndReply( 258 this,
259 data,
260 start_callback));
261 return;
262 }
263 data_ = data;
264
265 // Store callback before any OnFailed() calles to make it called on failure.
Lei Zhang 2014/09/16 19:57:36 typo: calls, same on line 333
Vitaly Buka (NO REVIEWS) 2014/09/16 22:10:37 Done.
266 start_callback_ = start_callback;
267
268 // NOTE: This process _must_ be sandboxed, otherwise the pdf dll will load
269 // gdiplus.dll, change how rendering happens, and not be able to correctly
270 // generate when sent to a metafile DC.
271 utility_process_host_ =
272 content::UtilityProcessHost::Create(
273 this, base::MessageLoop::current()->message_loop_proxy())
274 ->AsWeakPtr();
275 if (!utility_process_host_)
276 return OnFailed();
277 // Should reply with OnProcessStarted().
278 Send(new ChromeUtilityMsg_StartupPing);
279 }
280
281 void PdfToEmfUtilityProcessHostClient::OnProcessStarted() {
282 DCHECK_CURRENTLY_ON(BrowserThread::IO);
283 if (!utility_process_host_)
284 return OnFailed();
285
286 base::ProcessHandle process = utility_process_host_->GetData().handle;
287 scoped_refptr<base::RefCountedMemory> data = data_;
288 data_ = NULL;
289 BrowserThread::PostTaskAndReplyWithResult(
191 BrowserThread::FILE, 290 BrowserThread::FILE,
192 FROM_HERE, 291 FROM_HERE,
193 base::Bind(&FileHandlers::Init, files_, make_scoped_refptr(data)), 292 base::Bind(&CreateTempPdfFile, data),
194 base::Bind(&PdfToEmfUtilityProcessHostClient::OnFilesReadyOnUIThread, 293 base::Bind(&PdfToEmfUtilityProcessHostClient::OnTempPdfReady, this));
195 this)); 294 }
295
296 void PdfToEmfUtilityProcessHostClient::OnTempPdfReady(ScopedTempFile pdf) {
297 DCHECK_CURRENTLY_ON(BrowserThread::IO);
298 if (!utility_process_host_)
299 return OnFailed();
300 base::ProcessHandle process = utility_process_host_->GetData().handle;
301 // Should reply with OnPageCount().
302 Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles(
303 IPC::GetFileHandleForProcess(pdf->GetPlatformFile(), process, false),
304 settings_));
305 }
306
307 void PdfToEmfUtilityProcessHostClient::OnPageCount(int page_count) {
308 DCHECK_CURRENTLY_ON(BrowserThread::IO);
309 if (start_callback_.is_null())
310 return OnFailed();
311 BrowserThread::PostTask(BrowserThread::UI,
312 FROM_HERE,
313 base::Bind(&PdfToEmfConverterImpl::RunCallback,
314 converter_,
315 base::Bind(start_callback_, page_count)));
316 start_callback_.Reset();
317 }
318
319 void PdfToEmfUtilityProcessHostClient::GetPage(
320 int page_number,
321 const PdfToEmfConverter::GetPageCallback& get_page_callback) {
322 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
323 BrowserThread::PostTask(
324 BrowserThread::IO,
325 FROM_HERE,
326 base::Bind(&PdfToEmfUtilityProcessHostClient::GetPage,
327 this,
328 page_number,
329 get_page_callback));
330 return;
331 }
332
333 // Store callback before any OnFailed() calles to make it called on failure.
334 get_page_callbacks_.push(GetPageCallbackData(page_number, get_page_callback));
335
336 if (!utility_process_host_)
337 return OnFailed();
338
339 BrowserThread::PostTaskAndReplyWithResult(
340 BrowserThread::FILE,
341 FROM_HERE,
342 base::Bind(&CreateTempFile),
343 base::Bind(&PdfToEmfUtilityProcessHostClient::OnTempEmfReady,
344 this,
345 &get_page_callbacks_.back()));
346 }
347
348 void PdfToEmfUtilityProcessHostClient::OnTempEmfReady(
349 GetPageCallbackData* callback_data,
350 ScopedTempFile emf) {
351 DCHECK_CURRENTLY_ON(BrowserThread::IO);
352 if (!utility_process_host_)
353 return OnFailed();
354 base::ProcessHandle process = utility_process_host_->GetData().handle;
355 IPC::PlatformFileForTransit transit =
356 IPC::GetFileHandleForProcess(emf->GetPlatformFile(), process, false);
357 callback_data->set_emf(emf.Pass());
358 // Should reply with OnPageDone().
359 Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage(
360 callback_data->page_number(), transit));
361 }
362
363 void PdfToEmfUtilityProcessHostClient::OnPageDone(bool success,
364 double scale_factor) {
365 DCHECK_CURRENTLY_ON(BrowserThread::IO);
366 if (get_page_callbacks_.empty())
367 return OnFailed();
368 scoped_ptr<LazyEmf> emf;
369 GetPageCallbackData& data = get_page_callbacks_.front();
370 if (success)
371 emf.reset(new LazyEmf(data.emf().Pass()));
372 BrowserThread::PostTask(BrowserThread::UI,
373 FROM_HERE,
374 base::Bind(&PdfToEmfConverterImpl::RunCallback,
375 converter_,
376 base::Bind(data.callback(),
377 data.page_number(),
378 scale_factor,
379 base::Passed(&emf))));
380 get_page_callbacks_.pop();
381 }
382
383 void PdfToEmfUtilityProcessHostClient::Stop() {
384 if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
385 BrowserThread::PostTask(
386 BrowserThread::IO,
387 FROM_HERE,
388 base::Bind(&PdfToEmfUtilityProcessHostClient::Stop, this));
389 return;
390 }
391 Send(new ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop());
196 } 392 }
197 393
198 void PdfToEmfUtilityProcessHostClient::OnProcessCrashed(int exit_code) { 394 void PdfToEmfUtilityProcessHostClient::OnProcessCrashed(int exit_code) {
199 OnFailed(); 395 OnFailed();
200 } 396 }
201 397
398 void PdfToEmfUtilityProcessHostClient::OnProcessLaunchFailed() {
399 OnFailed();
400 }
401
202 bool PdfToEmfUtilityProcessHostClient::OnMessageReceived( 402 bool PdfToEmfUtilityProcessHostClient::OnMessageReceived(
203 const IPC::Message& message) { 403 const IPC::Message& message) {
204 bool handled = true; 404 bool handled = true;
205 IPC_BEGIN_MESSAGE_MAP(PdfToEmfUtilityProcessHostClient, message) 405 IPC_BEGIN_MESSAGE_MAP(PdfToEmfUtilityProcessHostClient, message)
206 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ProcessStarted, OnProcessStarted) 406 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_ProcessStarted, OnProcessStarted)
207 IPC_MESSAGE_HANDLER( 407 IPC_MESSAGE_HANDLER(
208 ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_Succeeded, OnSucceeded) 408 ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount, OnPageCount)
209 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Failed, 409 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone,
210 OnFailed) 410 OnPageDone)
211 IPC_MESSAGE_UNHANDLED(handled = false) 411 IPC_MESSAGE_UNHANDLED(handled = false)
212 IPC_END_MESSAGE_MAP() 412 IPC_END_MESSAGE_MAP()
213 return handled; 413 return handled;
214 } 414 }
215 415
216 void PdfToEmfUtilityProcessHostClient::OnProcessStarted() { 416 bool PdfToEmfUtilityProcessHostClient::Send(IPC::Message* msg) {
217 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 417 if (utility_process_host_)
218 if (!utility_process_host_) { 418 return utility_process_host_->Send(msg);
219 RunCallbackOnUIThread(std::vector<printing::PageRange>(), 0.0); 419 delete msg;
220 return; 420 return false;
221 } 421 }
222 422
223 base::ProcessHandle process = utility_process_host_->GetData().handle; 423 void PdfToEmfUtilityProcessHostClient::OnFailed() {
224 utility_process_host_->Send( 424 DCHECK_CURRENTLY_ON(BrowserThread::IO);
225 new ChromeUtilityMsg_RenderPDFPagesToMetafiles( 425 if (!start_callback_.is_null())
226 files_->GetPdfForProcess(process), 426 OnPageCount(0);
227 files_->GetEmfPath(), 427 while (!get_page_callbacks_.empty())
228 settings_, 428 OnPageDone(false, 0.0);
229 std::vector<printing::PageRange>()));
230 utility_process_host_.reset(); 429 utility_process_host_.reset();
231 } 430 }
232 431
233 void PdfToEmfUtilityProcessHostClient::OnSucceeded( 432 PdfToEmfConverterImpl::PdfToEmfConverterImpl() : weak_ptr_factory_(this) {
234 const std::vector<printing::PageRange>& page_ranges,
235 double scale_factor) {
236 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
237 RunCallback(page_ranges, scale_factor);
238 }
239
240 void PdfToEmfUtilityProcessHostClient::OnFailed() {
241 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
242 RunCallback(std::vector<printing::PageRange>(), 0.0);
243 }
244
245 void PdfToEmfUtilityProcessHostClient::OnFilesReadyOnUIThread() {
246 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
247 if (!files_->IsValid()) {
248 RunCallbackOnUIThread(std::vector<printing::PageRange>(), 0.0);
249 return;
250 }
251 BrowserThread::PostTask(
252 BrowserThread::IO,
253 FROM_HERE,
254 base::Bind(&PdfToEmfUtilityProcessHostClient::StartProcessOnIOThread,
255 this));
256 }
257
258 void PdfToEmfUtilityProcessHostClient::StartProcessOnIOThread() {
259 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
260 utility_process_host_ =
261 content::UtilityProcessHost::Create(
262 this,
263 base::MessageLoop::current()->message_loop_proxy())->AsWeakPtr();
264 // NOTE: This process _must_ be sandboxed, otherwise the pdf dll will load
265 // gdiplus.dll, change how rendering happens, and not be able to correctly
266 // generate when sent to a metafile DC.
267 utility_process_host_->SetExposedDir(files_->GetBasePath());
268 utility_process_host_->Send(new ChromeUtilityMsg_StartupPing);
269 }
270
271 void PdfToEmfUtilityProcessHostClient::RunCallback(
272 const std::vector<printing::PageRange>& page_ranges,
273 double scale_factor) {
274 BrowserThread::PostTask(
275 BrowserThread::UI,
276 FROM_HERE,
277 base::Bind(&PdfToEmfUtilityProcessHostClient::RunCallbackOnUIThread,
278 this,
279 page_ranges,
280 scale_factor));
281 }
282
283 void PdfToEmfUtilityProcessHostClient::RunCallbackOnUIThread(
284 const std::vector<printing::PageRange>& page_ranges,
285 double scale_factor) {
286 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
287 ScopedVector<MetafilePlayer> pages;
288 std::vector<printing::PageRange>::const_iterator iter;
289 for (iter = page_ranges.begin(); iter != page_ranges.end(); ++iter) {
290 for (int page_number = iter->from; page_number <= iter->to; ++page_number) {
291 scoped_ptr<TempEmf> metafile(new TempEmf(files_));
292 if (!metafile->InitFromFile(files_->GetEmfPagePath(page_number))) {
293 NOTREACHED() << "Invalid metafile";
294 metafile.reset();
295 }
296 pages.push_back(metafile.release());
297 }
298 }
299 files_ = NULL;
300 if (!callback_.is_null()) {
301 callback_.Run(scale_factor, &pages);
302 callback_.Reset();
303 }
304 }
305
306 class PdfToEmfConverterImpl : public PdfToEmfConverter {
307 public:
308 PdfToEmfConverterImpl();
309
310 virtual ~PdfToEmfConverterImpl();
311
312 virtual void Start(base::RefCountedMemory* data,
313 const printing::PdfRenderSettings& conversion_settings,
314 const ResultCallback& callback) OVERRIDE;
315
316 private:
317 scoped_refptr<PdfToEmfUtilityProcessHostClient> utility_client_;
318 base::CancelableCallback<ResultCallback::RunType> callback_;
319
320 DISALLOW_COPY_AND_ASSIGN(PdfToEmfConverterImpl);
321 };
322
323 PdfToEmfConverterImpl::PdfToEmfConverterImpl() {
324 } 433 }
325 434
326 PdfToEmfConverterImpl::~PdfToEmfConverterImpl() { 435 PdfToEmfConverterImpl::~PdfToEmfConverterImpl() {
436 if (utility_client_)
437 utility_client_->Stop();
327 } 438 }
328 439
329 void PdfToEmfConverterImpl::Start( 440 void PdfToEmfConverterImpl::Start(
330 base::RefCountedMemory* data, 441 const scoped_refptr<base::RefCountedMemory>& data,
331 const printing::PdfRenderSettings& conversion_settings, 442 const PdfRenderSettings& conversion_settings,
332 const ResultCallback& callback) { 443 const StartCallback& start_callback) {
333 // Rebind cancelable callback to avoid calling callback if 444 DCHECK(!utility_client_);
334 // PdfToEmfConverterImpl is destroyed. 445 utility_client_ = new PdfToEmfUtilityProcessHostClient(
335 callback_.Reset(callback); 446 weak_ptr_factory_.GetWeakPtr(), conversion_settings);
336 utility_client_ = new PdfToEmfUtilityProcessHostClient(conversion_settings); 447 utility_client_->Start(data, start_callback);
337 utility_client_->Convert(data, callback_.callback()); 448 }
449
450 void PdfToEmfConverterImpl::GetPage(int page_number,
451 const GetPageCallback& get_page_callback) {
452 utility_client_->GetPage(page_number, get_page_callback);
453 }
454
455 void PdfToEmfConverterImpl::RunCallback(const base::Closure& callback) {
456 DCHECK_CURRENTLY_ON(BrowserThread::UI);
457 callback.Run();
338 } 458 }
339 459
340 } // namespace 460 } // namespace
341 461
462 PdfToEmfConverter::~PdfToEmfConverter() {
463 }
464
342 // static 465 // static
343 scoped_ptr<PdfToEmfConverter> PdfToEmfConverter::CreateDefault() { 466 scoped_ptr<PdfToEmfConverter> PdfToEmfConverter::CreateDefault() {
344 return scoped_ptr<PdfToEmfConverter>(new PdfToEmfConverterImpl()); 467 return scoped_ptr<PdfToEmfConverter>(new PdfToEmfConverterImpl());
345 } 468 }
346 469
347 } // namespace printing 470 } // namespace printing
OLDNEW
« no previous file with comments | « chrome/browser/printing/pdf_to_emf_converter.h ('k') | chrome/browser/printing/print_job.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698