1// Copyright (c) 2010 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.
4
5#include <limits.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9
10#include <list>
11#include <sstream>
12#include <string>
13#include <utility>
14#include <vector>
15
16#include "../public/fpdf_dataavail.h"
17#include "../public/fpdf_ext.h"
18#include "../public/fpdf_formfill.h"
19#include "../public/fpdf_text.h"
20#include "../public/fpdfview.h"
21#include "image_diff_png.h"
22#include "v8/include/libplatform/libplatform.h"
23#include "v8/include/v8.h"
24
25#ifdef _WIN32
26#define snprintf _snprintf
27#define PATH_SEPARATOR '\\'
28#else
29#define PATH_SEPARATOR '/'
30#endif
31
32enum OutputFormat {
33  OUTPUT_NONE,
34  OUTPUT_PPM,
35  OUTPUT_PNG,
36#ifdef _WIN32
37  OUTPUT_BMP,
38  OUTPUT_EMF,
39#endif
40};
41
42struct Options {
43  Options() : output_format(OUTPUT_NONE) { }
44
45  OutputFormat output_format;
46  std::string scale_factor_as_string;
47  std::string exe_path;
48  std::string bin_directory;
49};
50
51// Reads the entire contents of a file into a newly malloc'd buffer.
52static char* GetFileContents(const char* filename, size_t* retlen) {
53  FILE* file = fopen(filename, "rb");
54  if (!file) {
55    fprintf(stderr, "Failed to open: %s\n", filename);
56    return NULL;
57  }
58  (void) fseek(file, 0, SEEK_END);
59  size_t file_length = ftell(file);
60  if (!file_length) {
61    return NULL;
62  }
63  (void) fseek(file, 0, SEEK_SET);
64  char* buffer = (char*) malloc(file_length);
65  if (!buffer) {
66    return NULL;
67  }
68  size_t bytes_read = fread(buffer, 1, file_length, file);
69  (void) fclose(file);
70  if (bytes_read != file_length) {
71    fprintf(stderr, "Failed to read: %s\n", filename);
72    free(buffer);
73    return NULL;
74  }
75  *retlen = bytes_read;
76  return buffer;
77}
78
79#ifdef V8_USE_EXTERNAL_STARTUP_DATA
80// Returns the full path for an external V8 data file based on either
81// the currect exectuable path or an explicit override.
82static std::string GetFullPathForSnapshotFile(const Options& options,
83                                              const std::string& filename) {
84  std::string result;
85  if (!options.bin_directory.empty()) {
86    result = options.bin_directory;
87    if (*options.bin_directory.rbegin() != PATH_SEPARATOR) {
88      result += PATH_SEPARATOR;
89    }
90  } else if (!options.exe_path.empty()) {
91    size_t last_separator = options.exe_path.rfind(PATH_SEPARATOR);
92    if (last_separator != std::string::npos)  {
93      result = options.exe_path.substr(0, last_separator + 1);
94    }
95  }
96  result += filename;
97  return result;
98}
99
100// Reads an extenal V8 data file from the |options|-indicated location,
101// returing true on success and false on error.
102static bool GetExternalData(const Options& options,
103                            const std::string& bin_filename,
104                            v8::StartupData* result_data) {
105  std::string full_path = GetFullPathForSnapshotFile(options, bin_filename);
106  size_t data_length = 0;
107  char* data_buffer = GetFileContents(full_path.c_str(), &data_length);
108  if (!data_buffer) {
109    return false;
110  }
111  result_data->data = const_cast<const char*>(data_buffer);
112  result_data->raw_size = static_cast<int>(data_length);
113  return true;
114}
115#endif  // V8_USE_EXTERNAL_STARTUP_DATA
116
117static bool CheckDimensions(int stride, int width, int height) {
118  if (stride < 0 || width < 0 || height < 0)
119    return false;
120  if (height > 0 && width > INT_MAX / height)
121    return false;
122  return true;
123}
124
125static void WritePpm(const char* pdf_name, int num, const void* buffer_void,
126                     int stride, int width, int height) {
127  const char* buffer = reinterpret_cast<const char*>(buffer_void);
128
129  if (!CheckDimensions(stride, width, height))
130    return;
131
132  int out_len = width * height;
133  if (out_len > INT_MAX / 3)
134    return;
135  out_len *= 3;
136
137  char filename[256];
138  snprintf(filename, sizeof(filename), "%s.%d.ppm", pdf_name, num);
139  FILE* fp = fopen(filename, "wb");
140  if (!fp)
141    return;
142  fprintf(fp, "P6\n# PDF test render\n%d %d\n255\n", width, height);
143  // Source data is B, G, R, unused.
144  // Dest data is R, G, B.
145  char* result = new char[out_len];
146  if (result) {
147    for (int h = 0; h < height; ++h) {
148      const char* src_line = buffer + (stride * h);
149      char* dest_line = result + (width * h * 3);
150      for (int w = 0; w < width; ++w) {
151        // R
152        dest_line[w * 3] = src_line[(w * 4) + 2];
153        // G
154        dest_line[(w * 3) + 1] = src_line[(w * 4) + 1];
155        // B
156        dest_line[(w * 3) + 2] = src_line[w * 4];
157      }
158    }
159    fwrite(result, out_len, 1, fp);
160    delete [] result;
161  }
162  fclose(fp);
163}
164
165static void WritePng(const char* pdf_name, int num, const void* buffer_void,
166                     int stride, int width, int height) {
167  if (!CheckDimensions(stride, width, height))
168    return;
169
170  std::vector<unsigned char> png_encoding;
171  const unsigned char* buffer = static_cast<const unsigned char*>(buffer_void);
172  if (!image_diff_png::EncodeBGRAPNG(
173          buffer, width, height, stride, false, &png_encoding)) {
174    fprintf(stderr, "Failed to convert bitmap to PNG\n");
175    return;
176  }
177
178  char filename[256];
179  int chars_formatted = snprintf(
180      filename, sizeof(filename), "%s.%d.png", pdf_name, num);
181  if (chars_formatted < 0 ||
182      static_cast<size_t>(chars_formatted) >= sizeof(filename)) {
183    fprintf(stderr, "Filname %s is too long\n", filename);
184    return;
185  }
186
187  FILE* fp = fopen(filename, "wb");
188  if (!fp) {
189    fprintf(stderr, "Failed to open %s for output\n", filename);
190    return;
191  }
192
193  size_t bytes_written = fwrite(
194      &png_encoding.front(), 1, png_encoding.size(), fp);
195  if (bytes_written != png_encoding.size())
196    fprintf(stderr, "Failed to write to  %s\n", filename);
197
198  (void) fclose(fp);
199}
200
201#ifdef _WIN32
202static void WriteBmp(const char* pdf_name, int num, const void* buffer,
203                     int stride, int width, int height) {
204  if (stride < 0 || width < 0 || height < 0)
205    return;
206  if (height > 0 && width > INT_MAX / height)
207    return;
208  int out_len = stride * height;
209  if (out_len > INT_MAX / 3)
210    return;
211
212  char filename[256];
213  snprintf(filename, sizeof(filename), "%s.%d.bmp", pdf_name, num);
214  FILE* fp = fopen(filename, "wb");
215  if (!fp)
216    return;
217
218  BITMAPINFO bmi = {0};
219  bmi.bmiHeader.biSize = sizeof(bmi) - sizeof(RGBQUAD);
220  bmi.bmiHeader.biWidth = width;
221  bmi.bmiHeader.biHeight = -height;  // top-down image
222  bmi.bmiHeader.biPlanes = 1;
223  bmi.bmiHeader.biBitCount = 32;
224  bmi.bmiHeader.biCompression = BI_RGB;
225  bmi.bmiHeader.biSizeImage = 0;
226
227  BITMAPFILEHEADER file_header = {0};
228  file_header.bfType = 0x4d42;
229  file_header.bfSize = sizeof(file_header) + bmi.bmiHeader.biSize + out_len;
230  file_header.bfOffBits = file_header.bfSize - out_len;
231
232  fwrite(&file_header, sizeof(file_header), 1, fp);
233  fwrite(&bmi, bmi.bmiHeader.biSize, 1, fp);
234  fwrite(buffer, out_len, 1, fp);
235  fclose(fp);
236}
237
238void WriteEmf(FPDF_PAGE page, const char* pdf_name, int num) {
239  int width = static_cast<int>(FPDF_GetPageWidth(page));
240  int height = static_cast<int>(FPDF_GetPageHeight(page));
241
242  char filename[256];
243  snprintf(filename, sizeof(filename), "%s.%d.emf", pdf_name, num);
244
245  HDC dc = CreateEnhMetaFileA(NULL, filename, NULL, NULL);
246
247  HRGN rgn = CreateRectRgn(0, 0, width, height);
248  SelectClipRgn(dc, rgn);
249  DeleteObject(rgn);
250
251  SelectObject(dc, GetStockObject(NULL_PEN));
252  SelectObject(dc, GetStockObject(WHITE_BRUSH));
253  // If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less.
254  Rectangle(dc, 0, 0, width + 1, height + 1);
255
256  FPDF_RenderPage(dc, page, 0, 0, width, height, 0,
257                  FPDF_ANNOT | FPDF_PRINTING | FPDF_NO_CATCH);
258
259  DeleteEnhMetaFile(CloseEnhMetaFile(dc));
260}
261#endif
262
263int ExampleAppAlert(IPDF_JSPLATFORM*, FPDF_WIDESTRING msg, FPDF_WIDESTRING,
264                    int, int) {
265  // Deal with differences between UTF16LE and wchar_t on this platform.
266  size_t characters = 0;
267  while (msg[characters]) {
268    ++characters;
269  }
270  wchar_t* platform_string =
271      (wchar_t*)malloc((characters + 1) * sizeof(wchar_t));
272  for (size_t i = 0; i < characters + 1; ++i) {
273    unsigned char* ptr = (unsigned char*)&msg[i];
274    platform_string[i] = ptr[0] + 256 * ptr[1];
275  }
276  printf("Alert: %ls\n", platform_string);
277  free(platform_string);
278  return 0;
279}
280
281void ExampleDocGotoPage(IPDF_JSPLATFORM*, int pageNumber) {
282  printf("Goto Page: %d\n", pageNumber);
283}
284
285void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {
286  std::string feature = "Unknown";
287  switch (type) {
288    case FPDF_UNSP_DOC_XFAFORM:
289      feature = "XFA";
290      break;
291    case FPDF_UNSP_DOC_PORTABLECOLLECTION:
292      feature = "Portfolios_Packages";
293      break;
294    case FPDF_UNSP_DOC_ATTACHMENT:
295    case FPDF_UNSP_ANNOT_ATTACHMENT:
296      feature = "Attachment";
297      break;
298    case FPDF_UNSP_DOC_SECURITY:
299      feature = "Rights_Management";
300      break;
301    case FPDF_UNSP_DOC_SHAREDREVIEW:
302      feature = "Shared_Review";
303      break;
304    case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
305    case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
306    case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
307      feature = "Shared_Form";
308      break;
309    case FPDF_UNSP_ANNOT_3DANNOT:
310      feature = "3D";
311      break;
312    case FPDF_UNSP_ANNOT_MOVIE:
313      feature = "Movie";
314      break;
315    case FPDF_UNSP_ANNOT_SOUND:
316      feature = "Sound";
317      break;
318    case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
319    case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
320      feature = "Screen";
321      break;
322    case FPDF_UNSP_ANNOT_SIG:
323      feature = "Digital_Signature";
324      break;
325  }
326  printf("Unsupported feature: %s.\n", feature.c_str());
327}
328
329bool ParseCommandLine(const std::vector<std::string>& args,
330                      Options* options, std::list<std::string>* files) {
331  if (args.empty()) {
332    return false;
333  }
334  options->exe_path = args[0];
335  size_t cur_idx = 1;
336  for (; cur_idx < args.size(); ++cur_idx) {
337    const std::string& cur_arg = args[cur_idx];
338    if (cur_arg == "--ppm") {
339      if (options->output_format != OUTPUT_NONE) {
340        fprintf(stderr, "Duplicate or conflicting --ppm argument\n");
341        return false;
342      }
343      options->output_format = OUTPUT_PPM;
344    } else if (cur_arg == "--png") {
345      if (options->output_format != OUTPUT_NONE) {
346        fprintf(stderr, "Duplicate or conflicting --png argument\n");
347        return false;
348      }
349      options->output_format = OUTPUT_PNG;
350    }
351#ifdef _WIN32
352    else if (cur_arg == "--emf") {
353      if (options->output_format != OUTPUT_NONE) {
354        fprintf(stderr, "Duplicate or conflicting --emf argument\n");
355        return false;
356      }
357      options->output_format = OUTPUT_EMF;
358    }
359    else if (cur_arg == "--bmp") {
360      if (options->output_format != OUTPUT_NONE) {
361        fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
362        return false;
363      }
364      options->output_format = OUTPUT_BMP;
365    }
366#endif  // _WIN32
367#ifdef V8_USE_EXTERNAL_STARTUP_DATA
368    else if (cur_arg.size() > 10 && cur_arg.compare(0, 10, "--bin-dir=") == 0) {
369      if (!options->bin_directory.empty()) {
370        fprintf(stderr, "Duplicate --bin-dir argument\n");
371        return false;
372      }
373      options->bin_directory = cur_arg.substr(10);
374    }
375#endif  // V8_USE_EXTERNAL_STARTUP_DATA
376    else if (cur_arg.size() > 8 && cur_arg.compare(0, 8, "--scale=") == 0) {
377      if (!options->scale_factor_as_string.empty()) {
378        fprintf(stderr, "Duplicate --scale argument\n");
379        return false;
380      }
381      options->scale_factor_as_string = cur_arg.substr(8);
382    }
383    else
384      break;
385  }
386  if (cur_idx >= args.size()) {
387    fprintf(stderr, "No input files.\n");
388    return false;
389  }
390  for (size_t i = cur_idx; i < args.size(); i++) {
391    files->push_back(args[i]);
392  }
393  return true;
394}
395
396class TestLoader {
397 public:
398  TestLoader(const char* pBuf, size_t len);
399
400  const char* m_pBuf;
401  size_t m_Len;
402};
403
404TestLoader::TestLoader(const char* pBuf, size_t len)
405    : m_pBuf(pBuf), m_Len(len) {
406}
407
408int Get_Block(void* param, unsigned long pos, unsigned char* pBuf,
409              unsigned long size) {
410  TestLoader* pLoader = (TestLoader*) param;
411  if (pos + size < pos || pos + size > pLoader->m_Len) return 0;
412  memcpy(pBuf, pLoader->m_pBuf + pos, size);
413  return 1;
414}
415
416FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* pThis, size_t offset, size_t size) {
417  return true;
418}
419
420void Add_Segment(FX_DOWNLOADHINTS* pThis, size_t offset, size_t size) {
421}
422
423void RenderPdf(const std::string& name, const char* pBuf, size_t len,
424               const Options& options) {
425  fprintf(stderr, "Rendering PDF file %s.\n", name.c_str());
426
427  IPDF_JSPLATFORM platform_callbacks;
428  memset(&platform_callbacks, '\0', sizeof(platform_callbacks));
429  platform_callbacks.version = 1;
430  platform_callbacks.app_alert = ExampleAppAlert;
431  platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
432
433  FPDF_FORMFILLINFO form_callbacks;
434  memset(&form_callbacks, '\0', sizeof(form_callbacks));
435  form_callbacks.version = 1;
436  form_callbacks.m_pJsPlatform = &platform_callbacks;
437
438  TestLoader loader(pBuf, len);
439
440  FPDF_FILEACCESS file_access;
441  memset(&file_access, '\0', sizeof(file_access));
442  file_access.m_FileLen = static_cast<unsigned long>(len);
443  file_access.m_GetBlock = Get_Block;
444  file_access.m_Param = &loader;
445
446  FX_FILEAVAIL file_avail;
447  memset(&file_avail, '\0', sizeof(file_avail));
448  file_avail.version = 1;
449  file_avail.IsDataAvail = Is_Data_Avail;
450
451  FX_DOWNLOADHINTS hints;
452  memset(&hints, '\0', sizeof(hints));
453  hints.version = 1;
454  hints.AddSegment = Add_Segment;
455
456  FPDF_DOCUMENT doc;
457  FPDF_AVAIL pdf_avail = FPDFAvail_Create(&file_avail, &file_access);
458
459  (void) FPDFAvail_IsDocAvail(pdf_avail, &hints);
460
461  if (!FPDFAvail_IsLinearized(pdf_avail)) {
462    fprintf(stderr, "Non-linearized path...\n");
463    doc = FPDF_LoadCustomDocument(&file_access, NULL);
464  } else {
465    fprintf(stderr, "Linearized path...\n");
466    doc = FPDFAvail_GetDocument(pdf_avail, NULL);
467  }
468
469  (void) FPDF_GetDocPermissions(doc);
470  (void) FPDFAvail_IsFormAvail(pdf_avail, &hints);
471
472  FPDF_FORMHANDLE form = FPDFDOC_InitFormFillEnvironment(doc, &form_callbacks);
473  FPDF_SetFormFieldHighlightColor(form, 0, 0xFFE4DD);
474  FPDF_SetFormFieldHighlightAlpha(form, 100);
475
476  int first_page = FPDFAvail_GetFirstPageNum(doc);
477  (void) FPDFAvail_IsPageAvail(pdf_avail, first_page, &hints);
478
479  int page_count = FPDF_GetPageCount(doc);
480  for (int i = 0; i < page_count; ++i) {
481    (void) FPDFAvail_IsPageAvail(pdf_avail, i, &hints);
482  }
483
484  FORM_DoDocumentJSAction(form);
485  FORM_DoDocumentOpenAction(form);
486
487  int rendered_pages = 0;
488  int bad_pages = 0;
489  for (int i = 0; i < page_count; ++i) {
490    FPDF_PAGE page = FPDF_LoadPage(doc, i);
491    if (!page) {
492        bad_pages ++;
493        continue;
494    }
495    FPDF_TEXTPAGE text_page = FPDFText_LoadPage(page);
496    FORM_OnAfterLoadPage(page, form);
497    FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_OPEN);
498
499    double scale = 1.0;
500    if (!options.scale_factor_as_string.empty()) {
501      std::stringstream(options.scale_factor_as_string) >> scale;
502    }
503    int width = static_cast<int>(FPDF_GetPageWidth(page) * scale);
504    int height = static_cast<int>(FPDF_GetPageHeight(page) * scale);
505
506    FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
507    if (!bitmap) {
508      fprintf(stderr, "Page was too large to be rendered.\n");
509      bad_pages++;
510      continue;
511    }
512
513    FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
514    FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
515    rendered_pages ++;
516
517    FPDF_FFLDraw(form, bitmap, page, 0, 0, width, height, 0, 0);
518    int stride = FPDFBitmap_GetStride(bitmap);
519    const char* buffer =
520        reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bitmap));
521
522    switch (options.output_format) {
523#ifdef _WIN32
524      case OUTPUT_BMP:
525        WriteBmp(name.c_str(), i, buffer, stride, width, height);
526        break;
527
528      case OUTPUT_EMF:
529        WriteEmf(page, name.c_str(), i);
530        break;
531#endif
532      case OUTPUT_PNG:
533        WritePng(name.c_str(), i, buffer, stride, width, height);
534        break;
535
536      case OUTPUT_PPM:
537        WritePpm(name.c_str(), i, buffer, stride, width, height);
538        break;
539
540      default:
541        break;
542    }
543
544    FPDFBitmap_Destroy(bitmap);
545
546    FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
547    FORM_OnBeforeClosePage(page, form);
548    FPDFText_ClosePage(text_page);
549    FPDF_ClosePage(page);
550  }
551
552  FORM_DoDocumentAAction(form, FPDFDOC_AACTION_WC);
553  FPDF_CloseDocument(doc);
554  FPDFDOC_ExitFormFillEnvironment(form);
555  FPDFAvail_Destroy(pdf_avail);
556
557  fprintf(stderr, "Rendered %d pages.\n", rendered_pages);
558  fprintf(stderr, "Skipped %d bad pages.\n", bad_pages);
559}
560
561static const char usage_string[] =
562    "Usage: pdfium_test [OPTION] [FILE]...\n"
563    "  --bin-dir=<path> - override path to v8 external data\n"
564    "  --scale=<number> - scale output size by number (e.g. 0.5)\n"
565#ifdef _WIN32
566    "  --bmp - write page images <pdf-name>.<page-number>.bmp\n"
567    "  --emf - write page meta files <pdf-name>.<page-number>.emf\n"
568#endif
569    "  --png - write page images <pdf-name>.<page-number>.png\n"
570    "  --ppm - write page images <pdf-name>.<page-number>.ppm\n";
571
572int main(int argc, const char* argv[]) {
573  std::vector<std::string> args(argv, argv + argc);
574  Options options;
575  std::list<std::string> files;
576  if (!ParseCommandLine(args, &options, &files)) {
577    fprintf(stderr, "%s", usage_string);
578    return 1;
579  }
580
581  v8::V8::InitializeICU();
582  v8::Platform* platform = v8::platform::CreateDefaultPlatform();
583  v8::V8::InitializePlatform(platform);
584  v8::V8::Initialize();
585
586  // By enabling predictable mode, V8 won't post any background tasks.
587  static const char predictable_flag[] = "--predictable";
588  v8::V8::SetFlagsFromString(predictable_flag,
589                             static_cast<int>(strlen(predictable_flag)));
590
591#ifdef V8_USE_EXTERNAL_STARTUP_DATA
592  v8::StartupData natives;
593  v8::StartupData snapshot;
594  if (!GetExternalData(options, "natives_blob.bin", &natives) ||
595      !GetExternalData(options, "snapshot_blob.bin", &snapshot)) {
596    return 1;
597  }
598  v8::V8::SetNativesDataBlob(&natives);
599  v8::V8::SetSnapshotDataBlob(&snapshot);
600#endif  // V8_USE_EXTERNAL_STARTUP_DATA
601
602  FPDF_InitLibrary();
603
604  UNSUPPORT_INFO unsuppored_info;
605  memset(&unsuppored_info, '\0', sizeof(unsuppored_info));
606  unsuppored_info.version = 1;
607  unsuppored_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
608
609  FSDK_SetUnSpObjProcessHandler(&unsuppored_info);
610
611  while (!files.empty()) {
612    std::string filename = files.front();
613    files.pop_front();
614    size_t file_length = 0;
615    char* file_contents = GetFileContents(filename.c_str(), &file_length);
616    if (!file_contents)
617      continue;
618    RenderPdf(filename, file_contents, file_length, options);
619    free(file_contents);
620  }
621
622  FPDF_DestroyLibrary();
623  v8::V8::ShutdownPlatform();
624  delete platform;
625
626  return 0;
627}
628