Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / utility / chrome_content_utility_client.cc
blob9c883f5161fb9b962c82f314a635035691fdaf93
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/utility/chrome_content_utility_client.h"
7 #include "base/base64.h"
8 #include "base/bind.h"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/files/file_path.h"
12 #include "base/json/json_reader.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/path_service.h"
15 #include "base/scoped_native_library.h"
16 #include "base/time/time.h"
17 #include "chrome/common/chrome_paths.h"
18 #include "chrome/common/chrome_utility_messages.h"
19 #include "chrome/common/extensions/chrome_extensions_client.h"
20 #include "chrome/common/extensions/extension_l10n_util.h"
21 #include "chrome/common/extensions/update_manifest.h"
22 #include "chrome/common/safe_browsing/zip_analyzer.h"
23 #include "chrome/utility/cloud_print/bitmap_image.h"
24 #include "chrome/utility/cloud_print/pwg_encoder.h"
25 #include "chrome/utility/extensions/unpacker.h"
26 #include "chrome/utility/profile_import_handler.h"
27 #include "chrome/utility/web_resource_unpacker.h"
28 #include "content/public/child/image_decoder_utils.h"
29 #include "content/public/common/content_paths.h"
30 #include "content/public/utility/utility_thread.h"
31 #include "extensions/common/extension.h"
32 #include "extensions/common/manifest.h"
33 #include "media/base/media.h"
34 #include "media/base/media_file_checker.h"
35 #include "printing/page_range.h"
36 #include "printing/pdf_render_settings.h"
37 #include "third_party/skia/include/core/SkBitmap.h"
38 #include "third_party/zlib/google/zip.h"
39 #include "ui/base/ui_base_switches.h"
40 #include "ui/gfx/codec/jpeg_codec.h"
41 #include "ui/gfx/rect.h"
42 #include "ui/gfx/size.h"
44 #if defined(OS_WIN)
45 #include "base/win/iat_patch_function.h"
46 #include "base/win/scoped_handle.h"
47 #include "chrome/utility/media_galleries/itunes_pref_parser_win.h"
48 #include "printing/emf_win.h"
49 #include "ui/gfx/gdi_util.h"
50 #endif // defined(OS_WIN)
52 #if defined(OS_MACOSX)
53 #include "chrome/utility/media_galleries/iphoto_library_parser.h"
54 #endif // defined(OS_MACOSX)
56 #if defined(OS_WIN) || defined(OS_MACOSX)
57 #include "chrome/utility/media_galleries/iapps_xml_utils.h"
58 #include "chrome/utility/media_galleries/itunes_library_parser.h"
59 #include "chrome/utility/media_galleries/picasa_album_table_reader.h"
60 #include "chrome/utility/media_galleries/picasa_albums_indexer.h"
61 #endif // defined(OS_WIN) || defined(OS_MACOSX)
63 #if !defined(OS_ANDROID) && !defined(OS_IOS)
64 #include "chrome/utility/media_galleries/ipc_data_source.h"
65 #include "chrome/utility/media_galleries/media_metadata_parser.h"
66 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
68 #if defined(ENABLE_FULL_PRINTING)
69 #include "chrome/common/crash_keys.h"
70 #include "printing/backend/print_backend.h"
71 #endif
73 #if defined(ENABLE_MDNS)
74 #include "chrome/utility/local_discovery/service_discovery_message_handler.h"
75 #include "content/public/common/content_switches.h"
76 #endif // ENABLE_MDNS
78 namespace chrome {
80 namespace {
82 bool Send(IPC::Message* message) {
83 return content::UtilityThread::Get()->Send(message);
86 void ReleaseProcessIfNeeded() {
87 content::UtilityThread::Get()->ReleaseProcessIfNeeded();
90 class PdfFunctionsBase {
91 public:
92 PdfFunctionsBase() : render_pdf_to_bitmap_func_(NULL),
93 get_pdf_doc_info_func_(NULL) {}
95 bool Init() {
96 base::FilePath pdf_module_path;
97 if (!PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_module_path) ||
98 !base::PathExists(pdf_module_path)) {
99 return false;
102 pdf_lib_.Reset(base::LoadNativeLibrary(pdf_module_path, NULL));
103 if (!pdf_lib_.is_valid()) {
104 LOG(WARNING) << "Couldn't load PDF plugin";
105 return false;
108 render_pdf_to_bitmap_func_ =
109 reinterpret_cast<RenderPDFPageToBitmapProc>(
110 pdf_lib_.GetFunctionPointer("RenderPDFPageToBitmap"));
111 LOG_IF(WARNING, !render_pdf_to_bitmap_func_) <<
112 "Missing RenderPDFPageToBitmap";
114 get_pdf_doc_info_func_ =
115 reinterpret_cast<GetPDFDocInfoProc>(
116 pdf_lib_.GetFunctionPointer("GetPDFDocInfo"));
117 LOG_IF(WARNING, !get_pdf_doc_info_func_) << "Missing GetPDFDocInfo";
119 if (!render_pdf_to_bitmap_func_ || !get_pdf_doc_info_func_ ||
120 !PlatformInit(pdf_module_path, pdf_lib_)) {
121 Reset();
124 return IsValid();
127 bool IsValid() const {
128 return pdf_lib_.is_valid();
131 void Reset() {
132 pdf_lib_.Reset(NULL);
135 bool RenderPDFPageToBitmap(const void* pdf_buffer,
136 int pdf_buffer_size,
137 int page_number,
138 void* bitmap_buffer,
139 int bitmap_width,
140 int bitmap_height,
141 int dpi_x,
142 int dpi_y,
143 bool autorotate) {
144 if (!render_pdf_to_bitmap_func_)
145 return false;
146 return render_pdf_to_bitmap_func_(pdf_buffer, pdf_buffer_size, page_number,
147 bitmap_buffer, bitmap_width,
148 bitmap_height, dpi_x, dpi_y, autorotate);
151 bool GetPDFDocInfo(const void* pdf_buffer,
152 int buffer_size,
153 int* page_count,
154 double* max_page_width) {
155 if (!get_pdf_doc_info_func_)
156 return false;
157 return get_pdf_doc_info_func_(pdf_buffer, buffer_size, page_count,
158 max_page_width);
161 protected:
162 virtual bool PlatformInit(
163 const base::FilePath& pdf_module_path,
164 const base::ScopedNativeLibrary& pdf_lib) {
165 return true;
168 private:
169 // Exported by PDF plugin.
170 typedef bool (*RenderPDFPageToBitmapProc)(const void* pdf_buffer,
171 int pdf_buffer_size,
172 int page_number,
173 void* bitmap_buffer,
174 int bitmap_width,
175 int bitmap_height,
176 int dpi_x,
177 int dpi_y,
178 bool autorotate);
179 typedef bool (*GetPDFDocInfoProc)(const void* pdf_buffer,
180 int buffer_size, int* page_count,
181 double* max_page_width);
183 RenderPDFPageToBitmapProc render_pdf_to_bitmap_func_;
184 GetPDFDocInfoProc get_pdf_doc_info_func_;
186 base::ScopedNativeLibrary pdf_lib_;
187 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsBase);
190 #if defined(OS_WIN)
191 // The 2 below IAT patch functions are almost identical to the code in
192 // render_process_impl.cc. This is needed to work around specific Windows APIs
193 // used by the Chrome PDF plugin that will fail in the sandbox.
194 static base::win::IATPatchFunction g_iat_patch_createdca;
195 HDC WINAPI UtilityProcess_CreateDCAPatch(LPCSTR driver_name,
196 LPCSTR device_name,
197 LPCSTR output,
198 const DEVMODEA* init_data) {
199 if (driver_name && (std::string("DISPLAY") == driver_name)) {
200 // CreateDC fails behind the sandbox, but not CreateCompatibleDC.
201 return CreateCompatibleDC(NULL);
204 NOTREACHED();
205 return CreateDCA(driver_name, device_name, output, init_data);
208 static base::win::IATPatchFunction g_iat_patch_get_font_data;
209 DWORD WINAPI UtilityProcess_GetFontDataPatch(
210 HDC hdc, DWORD table, DWORD offset, LPVOID buffer, DWORD length) {
211 int rv = GetFontData(hdc, table, offset, buffer, length);
212 if (rv == GDI_ERROR && hdc) {
213 HFONT font = static_cast<HFONT>(GetCurrentObject(hdc, OBJ_FONT));
215 LOGFONT logfont;
216 if (GetObject(font, sizeof(LOGFONT), &logfont)) {
217 content::UtilityThread::Get()->PreCacheFont(logfont);
218 rv = GetFontData(hdc, table, offset, buffer, length);
219 content::UtilityThread::Get()->ReleaseCachedFonts();
222 return rv;
225 class PdfFunctionsWin : public PdfFunctionsBase {
226 public:
227 PdfFunctionsWin() : render_pdf_to_dc_func_(NULL) {
230 bool PlatformInit(
231 const base::FilePath& pdf_module_path,
232 const base::ScopedNativeLibrary& pdf_lib) OVERRIDE {
233 // Patch the IAT for handling specific APIs known to fail in the sandbox.
234 if (!g_iat_patch_createdca.is_patched()) {
235 g_iat_patch_createdca.Patch(pdf_module_path.value().c_str(),
236 "gdi32.dll", "CreateDCA",
237 UtilityProcess_CreateDCAPatch);
240 if (!g_iat_patch_get_font_data.is_patched()) {
241 g_iat_patch_get_font_data.Patch(pdf_module_path.value().c_str(),
242 "gdi32.dll", "GetFontData",
243 UtilityProcess_GetFontDataPatch);
245 render_pdf_to_dc_func_ =
246 reinterpret_cast<RenderPDFPageToDCProc>(
247 pdf_lib.GetFunctionPointer("RenderPDFPageToDC"));
248 LOG_IF(WARNING, !render_pdf_to_dc_func_) << "Missing RenderPDFPageToDC";
250 return render_pdf_to_dc_func_ != NULL;
253 bool RenderPDFPageToDC(const void* pdf_buffer,
254 int buffer_size,
255 int page_number,
256 HDC dc,
257 int dpi_x,
258 int dpi_y,
259 int bounds_origin_x,
260 int bounds_origin_y,
261 int bounds_width,
262 int bounds_height,
263 bool fit_to_bounds,
264 bool stretch_to_bounds,
265 bool keep_aspect_ratio,
266 bool center_in_bounds,
267 bool autorotate) {
268 if (!render_pdf_to_dc_func_)
269 return false;
270 return render_pdf_to_dc_func_(pdf_buffer, buffer_size, page_number,
271 dc, dpi_x, dpi_y, bounds_origin_x,
272 bounds_origin_y, bounds_width, bounds_height,
273 fit_to_bounds, stretch_to_bounds,
274 keep_aspect_ratio, center_in_bounds,
275 autorotate);
278 private:
279 // Exported by PDF plugin.
280 typedef bool (*RenderPDFPageToDCProc)(
281 const void* pdf_buffer, int buffer_size, int page_number, HDC dc,
282 int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y,
283 int bounds_width, int bounds_height, bool fit_to_bounds,
284 bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds,
285 bool autorotate);
286 RenderPDFPageToDCProc render_pdf_to_dc_func_;
288 DISALLOW_COPY_AND_ASSIGN(PdfFunctionsWin);
291 typedef PdfFunctionsWin PdfFunctions;
292 #else // OS_WIN
293 typedef PdfFunctionsBase PdfFunctions;
294 #endif // OS_WIN
296 #if !defined(OS_ANDROID) && !defined(OS_IOS)
297 void SendMediaMetadataToHost(
298 scoped_ptr<extensions::api::media_galleries::MediaMetadata> metadata) {
299 Send(new ChromeUtilityHostMsg_ParseMediaMetadata_Finished(
300 true, *(metadata->ToValue().get())));
302 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
304 static base::LazyInstance<PdfFunctions> g_pdf_lib = LAZY_INSTANCE_INITIALIZER;
306 } // namespace
308 ChromeContentUtilityClient::ChromeContentUtilityClient() {
309 #if !defined(OS_ANDROID)
310 handlers_.push_back(new ProfileImportHandler());
311 #endif // OS_ANDROID
313 #if defined(ENABLE_MDNS)
314 if (CommandLine::ForCurrentProcess()->HasSwitch(
315 switches::kUtilityProcessEnableMDns)) {
316 handlers_.push_back(new local_discovery::ServiceDiscoveryMessageHandler());
318 #endif // ENABLE_MDNS
321 ChromeContentUtilityClient::~ChromeContentUtilityClient() {
324 void ChromeContentUtilityClient::UtilityThreadStarted() {
325 CommandLine* command_line = CommandLine::ForCurrentProcess();
326 std::string lang = command_line->GetSwitchValueASCII(switches::kLang);
327 if (!lang.empty())
328 extension_l10n_util::SetProcessLocale(lang);
331 bool ChromeContentUtilityClient::OnMessageReceived(
332 const IPC::Message& message) {
333 bool handled = true;
334 IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
335 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackExtension, OnUnpackExtension)
336 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_UnpackWebResource,
337 OnUnpackWebResource)
338 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseUpdateManifest,
339 OnParseUpdateManifest)
340 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
341 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImageBase64, OnDecodeImageBase64)
342 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafile,
343 OnRenderPDFPagesToMetafile)
344 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToPWGRaster,
345 OnRenderPDFPagesToPWGRaster)
346 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
347 OnRobustJPEGDecodeImage)
348 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseJSON, OnParseJSON)
349 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_GetPrinterCapsAndDefaults,
350 OnGetPrinterCapsAndDefaults)
351 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
352 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
353 OnAnalyzeZipFileForDownloadProtection)
355 #if !defined(OS_ANDROID) && !defined(OS_IOS)
356 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CheckMediaFile, OnCheckMediaFile)
357 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
358 OnParseMediaMetadata)
359 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
361 #if defined(OS_CHROMEOS)
362 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
363 #endif // defined(OS_CHROMEOS)
365 #if defined(OS_WIN)
366 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesPrefXml,
367 OnParseITunesPrefXml)
368 #endif // defined(OS_WIN)
370 #if defined(OS_MACOSX)
371 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseIPhotoLibraryXmlFile,
372 OnParseIPhotoLibraryXmlFile)
373 #endif // defined(OS_MACOSX)
375 #if defined(OS_WIN) || defined(OS_MACOSX)
376 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseITunesLibraryXmlFile,
377 OnParseITunesLibraryXmlFile)
378 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParsePicasaPMPDatabase,
379 OnParsePicasaPMPDatabase)
380 IPC_MESSAGE_HANDLER(ChromeUtilityMsg_IndexPicasaAlbumsContents,
381 OnIndexPicasaAlbumsContents)
382 #endif // defined(OS_WIN) || defined(OS_MACOSX)
384 IPC_MESSAGE_UNHANDLED(handled = false)
385 IPC_END_MESSAGE_MAP()
387 for (Handlers::iterator it = handlers_.begin();
388 !handled && it != handlers_.end(); ++it) {
389 handled = (*it)->OnMessageReceived(message);
392 return handled;
395 // static
396 void ChromeContentUtilityClient::PreSandboxStartup() {
397 #if defined(ENABLE_MDNS)
398 local_discovery::ServiceDiscoveryMessageHandler::PreSandboxStartup();
399 #endif // ENABLE_MDNS
401 g_pdf_lib.Get().Init();
403 // Load media libraries for media file validation.
404 base::FilePath media_path;
405 PathService::Get(content::DIR_MEDIA_LIBS, &media_path);
406 if (!media_path.empty())
407 media::InitializeMediaLibrary(media_path);
410 void ChromeContentUtilityClient::OnUnpackExtension(
411 const base::FilePath& extension_path,
412 const std::string& extension_id,
413 int location,
414 int creation_flags) {
415 CHECK_GT(location, extensions::Manifest::INVALID_LOCATION);
416 CHECK_LT(location, extensions::Manifest::NUM_LOCATIONS);
417 extensions::ExtensionsClient::Set(
418 extensions::ChromeExtensionsClient::GetInstance());
419 extensions::Unpacker unpacker(
420 extension_path,
421 extension_id,
422 static_cast<extensions::Manifest::Location>(location),
423 creation_flags);
424 if (unpacker.Run() && unpacker.DumpImagesToFile() &&
425 unpacker.DumpMessageCatalogsToFile()) {
426 Send(new ChromeUtilityHostMsg_UnpackExtension_Succeeded(
427 *unpacker.parsed_manifest()));
428 } else {
429 Send(new ChromeUtilityHostMsg_UnpackExtension_Failed(
430 unpacker.error_message()));
433 ReleaseProcessIfNeeded();
436 void ChromeContentUtilityClient::OnUnpackWebResource(
437 const std::string& resource_data) {
438 // Parse json data.
439 // TODO(mrc): Add the possibility of a template that controls parsing, and
440 // the ability to download and verify images.
441 WebResourceUnpacker unpacker(resource_data);
442 if (unpacker.Run()) {
443 Send(new ChromeUtilityHostMsg_UnpackWebResource_Succeeded(
444 *unpacker.parsed_json()));
445 } else {
446 Send(new ChromeUtilityHostMsg_UnpackWebResource_Failed(
447 unpacker.error_message()));
450 ReleaseProcessIfNeeded();
453 void ChromeContentUtilityClient::OnParseUpdateManifest(const std::string& xml) {
454 UpdateManifest manifest;
455 if (!manifest.Parse(xml)) {
456 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Failed(
457 manifest.errors()));
458 } else {
459 Send(new ChromeUtilityHostMsg_ParseUpdateManifest_Succeeded(
460 manifest.results()));
462 ReleaseProcessIfNeeded();
465 void ChromeContentUtilityClient::OnDecodeImage(
466 const std::vector<unsigned char>& encoded_data) {
467 const SkBitmap& decoded_image = content::DecodeImage(&encoded_data[0],
468 gfx::Size(),
469 encoded_data.size());
470 if (decoded_image.empty()) {
471 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
472 } else {
473 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(decoded_image));
475 ReleaseProcessIfNeeded();
478 void ChromeContentUtilityClient::OnDecodeImageBase64(
479 const std::string& encoded_string) {
480 std::string decoded_string;
482 if (!base::Base64Decode(encoded_string, &decoded_string)) {
483 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
484 return;
487 std::vector<unsigned char> decoded_vector(decoded_string.size());
488 for (size_t i = 0; i < decoded_string.size(); ++i) {
489 decoded_vector[i] = static_cast<unsigned char>(decoded_string[i]);
492 OnDecodeImage(decoded_vector);
495 #if defined(OS_CHROMEOS)
496 void ChromeContentUtilityClient::OnCreateZipFile(
497 const base::FilePath& src_dir,
498 const std::vector<base::FilePath>& src_relative_paths,
499 const base::FileDescriptor& dest_fd) {
500 bool succeeded = true;
502 // Check sanity of source relative paths. Reject if path is absolute or
503 // contains any attempt to reference a parent directory ("../" tricks).
504 for (std::vector<base::FilePath>::const_iterator iter =
505 src_relative_paths.begin(); iter != src_relative_paths.end();
506 ++iter) {
507 if (iter->IsAbsolute() || iter->ReferencesParent()) {
508 succeeded = false;
509 break;
513 if (succeeded)
514 succeeded = zip::ZipFiles(src_dir, src_relative_paths, dest_fd.fd);
516 if (succeeded)
517 Send(new ChromeUtilityHostMsg_CreateZipFile_Succeeded());
518 else
519 Send(new ChromeUtilityHostMsg_CreateZipFile_Failed());
520 ReleaseProcessIfNeeded();
522 #endif // defined(OS_CHROMEOS)
524 void ChromeContentUtilityClient::OnRenderPDFPagesToMetafile(
525 base::PlatformFile pdf_file,
526 const base::FilePath& metafile_path,
527 const printing::PdfRenderSettings& settings,
528 const std::vector<printing::PageRange>& page_ranges) {
529 bool succeeded = false;
530 #if defined(OS_WIN)
531 int highest_rendered_page_number = 0;
532 double scale_factor = 1.0;
533 succeeded = RenderPDFToWinMetafile(pdf_file,
534 metafile_path,
535 settings,
536 page_ranges,
537 &highest_rendered_page_number,
538 &scale_factor);
539 if (succeeded) {
540 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Succeeded(
541 highest_rendered_page_number, scale_factor));
543 #endif // defined(OS_WIN)
544 if (!succeeded) {
545 Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafile_Failed());
547 ReleaseProcessIfNeeded();
550 void ChromeContentUtilityClient::OnRenderPDFPagesToPWGRaster(
551 IPC::PlatformFileForTransit pdf_transit,
552 const printing::PdfRenderSettings& settings,
553 IPC::PlatformFileForTransit bitmap_transit) {
554 base::PlatformFile pdf =
555 IPC::PlatformFileForTransitToPlatformFile(pdf_transit);
556 base::PlatformFile bitmap =
557 IPC::PlatformFileForTransitToPlatformFile(bitmap_transit);
558 if (RenderPDFPagesToPWGRaster(pdf, settings, bitmap)) {
559 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Succeeded());
560 } else {
561 Send(new ChromeUtilityHostMsg_RenderPDFPagesToPWGRaster_Failed());
563 ReleaseProcessIfNeeded();
566 #if defined(OS_WIN)
567 bool ChromeContentUtilityClient::RenderPDFToWinMetafile(
568 base::PlatformFile pdf_file,
569 const base::FilePath& metafile_path,
570 const printing::PdfRenderSettings& settings,
571 const std::vector<printing::PageRange>& page_ranges,
572 int* highest_rendered_page_number,
573 double* scale_factor) {
574 *highest_rendered_page_number = -1;
575 *scale_factor = 1.0;
576 base::win::ScopedHandle file(pdf_file);
578 if (!g_pdf_lib.Get().IsValid())
579 return false;
581 // TODO(sanjeevr): Add a method to the PDF DLL that takes in a file handle
582 // and a page range array. That way we don't need to read the entire PDF into
583 // memory.
584 DWORD length = ::GetFileSize(file, NULL);
585 if (length == INVALID_FILE_SIZE)
586 return false;
588 std::vector<uint8> buffer;
589 buffer.resize(length);
590 DWORD bytes_read = 0;
591 if (!ReadFile(pdf_file, &buffer.front(), length, &bytes_read, NULL) ||
592 (bytes_read != length)) {
593 return false;
596 int total_page_count = 0;
597 if (!g_pdf_lib.Get().GetPDFDocInfo(&buffer.front(), buffer.size(),
598 &total_page_count, NULL)) {
599 return false;
602 printing::Emf metafile;
603 metafile.InitToFile(metafile_path);
604 // We need to scale down DC to fit an entire page into DC available area.
605 // Current metafile is based on screen DC and have current screen size.
606 // Writing outside of those boundaries will result in the cut-off output.
607 // On metafiles (this is the case here), scaling down will still record
608 // original coordinates and we'll be able to print in full resolution.
609 // Before playback we'll need to counter the scaling up that will happen
610 // in the service (print_system_win.cc).
611 *scale_factor = gfx::CalculatePageScale(metafile.context(),
612 settings.area().right(),
613 settings.area().bottom());
614 gfx::ScaleDC(metafile.context(), *scale_factor);
616 bool ret = false;
617 std::vector<printing::PageRange>::const_iterator iter;
618 for (iter = page_ranges.begin(); iter != page_ranges.end(); ++iter) {
619 for (int page_number = iter->from; page_number <= iter->to; ++page_number) {
620 if (page_number >= total_page_count)
621 break;
622 // The underlying metafile is of type Emf and ignores the arguments passed
623 // to StartPage.
624 metafile.StartPage(gfx::Size(), gfx::Rect(), 1);
625 if (g_pdf_lib.Get().RenderPDFPageToDC(
626 &buffer.front(), buffer.size(), page_number, metafile.context(),
627 settings.dpi(), settings.dpi(), settings.area().x(),
628 settings.area().y(), settings.area().width(),
629 settings.area().height(), true, false, true, true,
630 settings.autorotate())) {
631 if (*highest_rendered_page_number < page_number)
632 *highest_rendered_page_number = page_number;
633 ret = true;
635 metafile.FinishPage();
638 metafile.FinishDocument();
639 return ret;
641 #endif // defined(OS_WIN)
643 bool ChromeContentUtilityClient::RenderPDFPagesToPWGRaster(
644 base::PlatformFile pdf_file,
645 const printing::PdfRenderSettings& settings,
646 base::PlatformFile bitmap_file) {
647 bool autoupdate = true;
648 if (!g_pdf_lib.Get().IsValid())
649 return false;
651 base::PlatformFileInfo info;
652 if (!base::GetPlatformFileInfo(pdf_file, &info) || info.size <= 0)
653 return false;
655 std::string data(info.size, 0);
656 int data_size = base::ReadPlatformFile(pdf_file, 0, &data[0], data.size());
657 if (data_size != static_cast<int>(data.size()))
658 return false;
660 int total_page_count = 0;
661 if (!g_pdf_lib.Get().GetPDFDocInfo(data.data(), data.size(),
662 &total_page_count, NULL)) {
663 return false;
666 cloud_print::PwgEncoder encoder;
667 std::string pwg_header;
668 encoder.EncodeDocumentHeader(&pwg_header);
669 int bytes_written = base::WritePlatformFileAtCurrentPos(bitmap_file,
670 pwg_header.data(),
671 pwg_header.size());
672 if (bytes_written != static_cast<int>(pwg_header.size()))
673 return false;
675 cloud_print::BitmapImage image(settings.area().size(),
676 cloud_print::BitmapImage::BGRA);
677 for (int i = 0; i < total_page_count; ++i) {
678 if (!g_pdf_lib.Get().RenderPDFPageToBitmap(
679 data.data(), data.size(), i, image.pixel_data(),
680 image.size().width(), image.size().height(), settings.dpi(),
681 settings.dpi(), autoupdate)) {
682 return false;
684 std::string pwg_page;
685 if (!encoder.EncodePage(image, settings.dpi(), total_page_count, &pwg_page))
686 return false;
687 bytes_written = base::WritePlatformFileAtCurrentPos(bitmap_file,
688 pwg_page.data(),
689 pwg_page.size());
690 if (bytes_written != static_cast<int>(pwg_page.size()))
691 return false;
693 return true;
696 void ChromeContentUtilityClient::OnRobustJPEGDecodeImage(
697 const std::vector<unsigned char>& encoded_data) {
698 // Our robust jpeg decoding is using IJG libjpeg.
699 if (gfx::JPEGCodec::JpegLibraryVariant() == gfx::JPEGCodec::IJG_LIBJPEG) {
700 scoped_ptr<SkBitmap> decoded_image(gfx::JPEGCodec::Decode(
701 &encoded_data[0], encoded_data.size()));
702 if (!decoded_image.get() || decoded_image->empty()) {
703 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
704 } else {
705 Send(new ChromeUtilityHostMsg_DecodeImage_Succeeded(*decoded_image));
707 } else {
708 Send(new ChromeUtilityHostMsg_DecodeImage_Failed());
710 ReleaseProcessIfNeeded();
713 void ChromeContentUtilityClient::OnParseJSON(const std::string& json) {
714 int error_code;
715 std::string error;
716 base::Value* value = base::JSONReader::ReadAndReturnError(
717 json, base::JSON_PARSE_RFC, &error_code, &error);
718 if (value) {
719 base::ListValue wrapper;
720 wrapper.Append(value);
721 Send(new ChromeUtilityHostMsg_ParseJSON_Succeeded(wrapper));
722 } else {
723 Send(new ChromeUtilityHostMsg_ParseJSON_Failed(error));
725 ReleaseProcessIfNeeded();
728 void ChromeContentUtilityClient::OnGetPrinterCapsAndDefaults(
729 const std::string& printer_name) {
730 #if defined(ENABLE_FULL_PRINTING)
731 scoped_refptr<printing::PrintBackend> print_backend =
732 printing::PrintBackend::CreateInstance(NULL);
733 printing::PrinterCapsAndDefaults printer_info;
735 crash_keys::ScopedPrinterInfo crash_key(
736 print_backend->GetPrinterDriverInfo(printer_name));
738 if (print_backend->GetPrinterCapsAndDefaults(printer_name, &printer_info)) {
739 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Succeeded(
740 printer_name, printer_info));
741 } else // NOLINT
742 #endif
744 Send(new ChromeUtilityHostMsg_GetPrinterCapsAndDefaults_Failed(
745 printer_name));
747 ReleaseProcessIfNeeded();
750 void ChromeContentUtilityClient::OnStartupPing() {
751 Send(new ChromeUtilityHostMsg_ProcessStarted);
752 // Don't release the process, we assume further messages are on the way.
755 void ChromeContentUtilityClient::OnAnalyzeZipFileForDownloadProtection(
756 const IPC::PlatformFileForTransit& zip_file) {
757 safe_browsing::zip_analyzer::Results results;
758 safe_browsing::zip_analyzer::AnalyzeZipFile(
759 IPC::PlatformFileForTransitToPlatformFile(zip_file), &results);
760 Send(new ChromeUtilityHostMsg_AnalyzeZipFileForDownloadProtection_Finished(
761 results));
762 ReleaseProcessIfNeeded();
765 #if !defined(OS_ANDROID) && !defined(OS_IOS)
766 void ChromeContentUtilityClient::OnCheckMediaFile(
767 int64 milliseconds_of_decoding,
768 const IPC::PlatformFileForTransit& media_file) {
769 media::MediaFileChecker checker(
770 base::File(IPC::PlatformFileForTransitToPlatformFile(media_file)));
771 const bool check_success = checker.Start(
772 base::TimeDelta::FromMilliseconds(milliseconds_of_decoding));
773 Send(new ChromeUtilityHostMsg_CheckMediaFile_Finished(check_success));
774 ReleaseProcessIfNeeded();
777 void ChromeContentUtilityClient::OnParseMediaMetadata(
778 const std::string& mime_type,
779 int64 total_size) {
780 // Only one IPCDataSource may be created and added to the list of handlers.
781 CHECK(!media_metadata_parser_);
782 metadata::IPCDataSource* source = new metadata::IPCDataSource(total_size);
783 handlers_.push_back(source);
785 media_metadata_parser_.reset(new metadata::MediaMetadataParser(source,
786 mime_type));
787 media_metadata_parser_->Start(base::Bind(&SendMediaMetadataToHost));
789 #endif // !defined(OS_ANDROID) && !defined(OS_IOS)
791 #if defined(OS_WIN)
792 void ChromeContentUtilityClient::OnParseITunesPrefXml(
793 const std::string& itunes_xml_data) {
794 base::FilePath library_path(
795 itunes::FindLibraryLocationInPrefXml(itunes_xml_data));
796 Send(new ChromeUtilityHostMsg_GotITunesDirectory(library_path));
797 ReleaseProcessIfNeeded();
799 #endif // defined(OS_WIN)
801 #if defined(OS_MACOSX)
802 void ChromeContentUtilityClient::OnParseIPhotoLibraryXmlFile(
803 const IPC::PlatformFileForTransit& iphoto_library_file) {
804 iphoto::IPhotoLibraryParser parser;
805 base::PlatformFile file =
806 IPC::PlatformFileForTransitToPlatformFile(iphoto_library_file);
807 bool result = parser.Parse(iapps::ReadPlatformFileAsString(file));
808 Send(new ChromeUtilityHostMsg_GotIPhotoLibrary(result, parser.library()));
809 ReleaseProcessIfNeeded();
811 #endif // defined(OS_MACOSX)
813 #if defined(OS_WIN) || defined(OS_MACOSX)
814 void ChromeContentUtilityClient::OnParseITunesLibraryXmlFile(
815 const IPC::PlatformFileForTransit& itunes_library_file) {
816 itunes::ITunesLibraryParser parser;
817 base::PlatformFile file =
818 IPC::PlatformFileForTransitToPlatformFile(itunes_library_file);
819 bool result = parser.Parse(iapps::ReadPlatformFileAsString(file));
820 Send(new ChromeUtilityHostMsg_GotITunesLibrary(result, parser.library()));
821 ReleaseProcessIfNeeded();
824 void ChromeContentUtilityClient::OnParsePicasaPMPDatabase(
825 const picasa::AlbumTableFilesForTransit& album_table_files) {
826 picasa::AlbumTableFiles files;
827 files.indicator_file = IPC::PlatformFileForTransitToPlatformFile(
828 album_table_files.indicator_file);
829 files.category_file = IPC::PlatformFileForTransitToPlatformFile(
830 album_table_files.category_file);
831 files.date_file = IPC::PlatformFileForTransitToPlatformFile(
832 album_table_files.date_file);
833 files.filename_file = IPC::PlatformFileForTransitToPlatformFile(
834 album_table_files.filename_file);
835 files.name_file = IPC::PlatformFileForTransitToPlatformFile(
836 album_table_files.name_file);
837 files.token_file = IPC::PlatformFileForTransitToPlatformFile(
838 album_table_files.token_file);
839 files.uid_file = IPC::PlatformFileForTransitToPlatformFile(
840 album_table_files.uid_file);
842 picasa::PicasaAlbumTableReader reader(files);
843 bool parse_success = reader.Init();
844 Send(new ChromeUtilityHostMsg_ParsePicasaPMPDatabase_Finished(
845 parse_success,
846 reader.albums(),
847 reader.folders()));
848 ReleaseProcessIfNeeded();
851 void ChromeContentUtilityClient::OnIndexPicasaAlbumsContents(
852 const picasa::AlbumUIDSet& album_uids,
853 const std::vector<picasa::FolderINIContents>& folders_inis) {
854 picasa::PicasaAlbumsIndexer indexer(album_uids);
855 indexer.ParseFolderINI(folders_inis);
857 Send(new ChromeUtilityHostMsg_IndexPicasaAlbumsContents_Finished(
858 indexer.albums_images()));
859 ReleaseProcessIfNeeded();
861 #endif // defined(OS_WIN) || defined(OS_MACOSX)
863 } // namespace chrome