Do some IWYU cleanups.
[pdfium.git] / fpdfsdk / src / fpdfview.cpp
1 // Copyright 2014 PDFium 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 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6
7 #include "../../core/include/fxcodec/fx_codec.h"
8 #include "../../core/include/fxcrt/fx_safe_types.h"
9 #include "../../public/fpdf_ext.h"
10 #include "../../public/fpdf_progressive.h"
11 #include "../../public/fpdfview.h"
12 #include "../../third_party/base/nonstd_unique_ptr.h"
13 #include "../../third_party/base/numerics/safe_conversions_impl.h"
14 #include "../include/fsdk_define.h"
15 #include "../include/fsdk_mgr.h"
16 #include "../include/fsdk_rendercontext.h"
17
18 CPDF_CustomAccess::CPDF_CustomAccess(FPDF_FILEACCESS* pFileAccess)
19 {
20         if (pFileAccess)
21                 m_FileAccess = *pFileAccess;
22 }
23
24 FX_BOOL CPDF_CustomAccess::ReadBlock(void* buffer, FX_FILESIZE offset, size_t size)
25 {
26     if (offset < 0) {
27         return FALSE;
28     }
29     FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
30     newPos += offset;
31     if (!newPos.IsValid() || newPos.ValueOrDie() > m_FileAccess.m_FileLen) {
32         return FALSE;
33     }
34     return m_FileAccess.m_GetBlock(m_FileAccess.m_Param, offset,(uint8_t*) buffer, size);
35 }
36
37 //0 bit: FPDF_POLICY_MACHINETIME_ACCESS
38 static FX_DWORD foxit_sandbox_policy = 0xFFFFFFFF;
39
40 void FSDK_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
41 {
42         switch(policy)
43         {
44         case FPDF_POLICY_MACHINETIME_ACCESS:
45                 {
46                         if(enable)
47                                 foxit_sandbox_policy |= 0x01;
48                         else
49                                 foxit_sandbox_policy &= 0xFFFFFFFE;
50                 }
51                 break;
52         default:
53                 break;
54         }
55 }
56
57 FPDF_BOOL FSDK_IsSandBoxPolicyEnabled(FPDF_DWORD policy)
58 {
59         switch(policy)
60         {
61         case FPDF_POLICY_MACHINETIME_ACCESS:
62                 {
63                         if(foxit_sandbox_policy&0x01)
64                                 return TRUE;
65                         else
66                                 return FALSE;
67                 }
68                 break;
69         default:
70                 break;
71         }
72         return FALSE;
73 }
74
75
76 #ifndef _T
77 #define _T(x) x
78 #endif
79
80 #ifdef API5
81         CPDF_ModuleMgr* g_pModuleMgr = NULL;
82 #else
83         CCodec_ModuleMgr*       g_pCodecModule = NULL;
84 #endif
85
86 //extern CPDFSDK_FormFillApp* g_pFormFillApp;
87
88 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
89 class CFontMapper : public IPDF_FontMapper
90 {
91 public:
92         CFontMapper();
93         virtual ~CFontMapper();
94
95         virtual FT_Face FindSubstFont(
96                                                         CPDF_Document* pDoc,                            // [IN] The PDF document
97                                                         const CFX_ByteString& face_name,        // [IN] Original name
98                                                         FX_BOOL bTrueType,                                      // [IN] TrueType or Type1
99                                                         FX_DWORD flags,                                         // [IN] PDF font flags (see PDF Reference section 5.7.1)
100                                                         int font_weight,                                        // [IN] original font weight. 0 for not specified
101                                                         int CharsetCP,                                          // [IN] code page for charset (see Win32 GetACP())
102                                                         FX_BOOL bVertical,
103                                                         CPDF_SubstFont* pSubstFont                      // [OUT] Subst font data
104                                                 );
105
106         FT_Face m_SysFace;
107 };
108
109 CFontMapper* g_pFontMapper = NULL;
110 #endif          // #if _FX_OS_ == _FX_LINUX_EMBEDDED_
111
112 DLLEXPORT void STDCALL FPDF_InitLibrary()
113 {
114         g_pCodecModule = CCodec_ModuleMgr::Create();
115
116         CFX_GEModule::Create();
117         CFX_GEModule::Get()->SetCodecModule(g_pCodecModule);
118
119         CPDF_ModuleMgr::Create();
120         CPDF_ModuleMgr::Get()->SetCodecModule(g_pCodecModule);
121         CPDF_ModuleMgr::Get()->InitPageModule();
122         CPDF_ModuleMgr::Get()->InitRenderModule();
123         CPDF_ModuleMgr * pModuleMgr = CPDF_ModuleMgr::Get();
124         if ( pModuleMgr )
125         {
126                 pModuleMgr->LoadEmbeddedGB1CMaps();
127                 pModuleMgr->LoadEmbeddedJapan1CMaps();
128                 pModuleMgr->LoadEmbeddedCNS1CMaps();
129                 pModuleMgr->LoadEmbeddedKorea1CMaps();
130         }
131 }
132
133
134 DLLEXPORT void STDCALL FPDF_DestroyLibrary()
135 {
136
137 #if _FX_OS_ == _FX_LINUX_EMBEDDED_
138         if (g_pFontMapper) delete g_pFontMapper;
139 #endif
140 #ifdef API5
141         g_pModuleMgr->Destroy();
142 #else
143         CPDF_ModuleMgr::Destroy();
144         CFX_GEModule::Destroy();
145         g_pCodecModule->Destroy();
146 #endif
147 }
148
149 #ifndef _WIN32
150 int g_LastError;
151 void SetLastError(int err)
152 {
153         g_LastError = err;
154 }
155
156 int GetLastError()
157 {
158         return g_LastError;
159 }
160 #endif
161
162 void ProcessParseError(FX_DWORD err_code)
163 {
164         // Translate FPDFAPI error code to FPDFVIEW error code
165         switch (err_code) {
166                 case PDFPARSE_ERROR_FILE:
167                         err_code = FPDF_ERR_FILE;
168                         break;
169                 case PDFPARSE_ERROR_FORMAT:
170                         err_code = FPDF_ERR_FORMAT;
171                         break;
172                 case PDFPARSE_ERROR_PASSWORD:
173                         err_code = FPDF_ERR_PASSWORD;
174                         break;
175                 case PDFPARSE_ERROR_HANDLER:
176                         err_code = FPDF_ERR_SECURITY;
177                         break;
178         }
179         SetLastError(err_code);
180 }
181
182 DLLEXPORT void  STDCALL FPDF_SetSandBoxPolicy(FPDF_DWORD policy, FPDF_BOOL enable)
183 {
184         return FSDK_SetSandBoxPolicy(policy, enable);
185 }
186
187 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadDocument(FPDF_STRING file_path, FPDF_BYTESTRING password)
188 {
189         CPDF_Parser* pParser = new CPDF_Parser;
190         pParser->SetPassword(password);
191
192         FX_DWORD err_code = pParser->StartParse((const FX_CHAR*)file_path);
193         if (err_code) {
194                 delete pParser;
195                 ProcessParseError(err_code);
196                 return NULL;
197         }
198         return pParser->GetDocument();
199 }
200
201 extern void CheckUnSupportError(CPDF_Document * pDoc, FX_DWORD err_code);
202
203 class CMemFile final: public IFX_FileRead
204 {
205 public:
206         CMemFile(uint8_t* pBuf, FX_FILESIZE size):m_pBuf(pBuf),m_size(size) {}
207
208         virtual void                    Release() {delete this;}
209         virtual FX_FILESIZE             GetSize() {return m_size;}
210         virtual FX_BOOL                 ReadBlock(void* buffer, FX_FILESIZE offset, size_t size)
211         {
212             if (offset < 0) {
213                 return FALSE;
214             }
215             FX_SAFE_FILESIZE newPos = pdfium::base::checked_cast<FX_FILESIZE, size_t>(size);
216             newPos += offset;
217             if (!newPos.IsValid() || newPos.ValueOrDie() > (FX_DWORD)m_size) {
218                 return FALSE;
219             }
220             FXSYS_memcpy(buffer, m_pBuf+offset, size);
221             return TRUE;
222         }
223 private:
224         uint8_t* m_pBuf;
225         FX_FILESIZE m_size;
226 };
227 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password)
228 {
229         CPDF_Parser* pParser = new CPDF_Parser;
230         pParser->SetPassword(password);
231         CMemFile* pMemFile = new CMemFile((uint8_t*)data_buf, size);
232         FX_DWORD err_code = pParser->StartParse(pMemFile);
233         if (err_code) {
234                 delete pParser;
235                 ProcessParseError(err_code);
236                 return NULL;
237         }
238         CPDF_Document * pDoc = NULL;
239         pDoc = pParser?pParser->GetDocument():NULL;
240         CheckUnSupportError(pDoc, err_code);
241         return pParser->GetDocument();
242 }
243
244 DLLEXPORT FPDF_DOCUMENT STDCALL FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password)
245 {
246         CPDF_Parser* pParser = new CPDF_Parser;
247         pParser->SetPassword(password);
248         CPDF_CustomAccess* pFile = new CPDF_CustomAccess(pFileAccess);
249         FX_DWORD err_code = pParser->StartParse(pFile);
250         if (err_code) {
251                 delete pParser;
252                 ProcessParseError(err_code);
253                 return NULL;
254         }
255         CPDF_Document * pDoc = NULL;
256         pDoc = pParser?pParser->GetDocument():NULL;
257         CheckUnSupportError(pDoc, err_code);
258         return pParser->GetDocument();
259 }
260
261 DLLEXPORT FPDF_BOOL STDCALL FPDF_GetFileVersion(FPDF_DOCUMENT doc, int* fileVersion)
262 {
263         if(!doc||!fileVersion) return FALSE;
264         *fileVersion = 0;
265         CPDF_Document* pDoc = (CPDF_Document*)doc;
266         CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
267         if(!pParser)
268                 return FALSE;
269         *fileVersion = pParser->GetFileVersion();
270         return TRUE;
271 }
272
273 // jabdelmalek: changed return type from FX_DWORD to build on Linux (and match header).
274 DLLEXPORT unsigned long STDCALL FPDF_GetDocPermissions(FPDF_DOCUMENT document)
275 {
276         if (document == NULL) return 0;
277         CPDF_Document*pDoc = (CPDF_Document*)document;
278         CPDF_Parser* pParser =  (CPDF_Parser*)pDoc->GetParser();
279         CPDF_Dictionary* pDict = pParser->GetEncryptDict();
280         if (pDict == NULL) return (FX_DWORD)-1;
281
282         return pDict->GetInteger("P");
283 }
284
285 DLLEXPORT int STDCALL FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document)
286 {
287     if (document == NULL) return -1;
288     CPDF_Document*pDoc = (CPDF_Document*)document;
289     CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
290     CPDF_Dictionary* pDict = pParser->GetEncryptDict();
291     if (pDict == NULL) return -1;
292
293     return pDict->GetInteger("R");
294 }
295
296 DLLEXPORT int STDCALL FPDF_GetPageCount(FPDF_DOCUMENT document)
297 {
298         if (document == NULL) return 0;
299         return ((CPDF_Document*)document)->GetPageCount();
300 }
301
302 DLLEXPORT FPDF_PAGE STDCALL FPDF_LoadPage(FPDF_DOCUMENT document, int page_index)
303 {
304         if (document == NULL) return NULL;
305         if (page_index < 0 || page_index >= FPDF_GetPageCount(document)) return NULL;
306
307         CPDF_Document* pDoc = (CPDF_Document*)document;
308         if (pDoc == NULL) return NULL;
309         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
310         if (pDict == NULL) return NULL;
311         CPDF_Page* pPage = new CPDF_Page;
312         pPage->Load(pDoc, pDict);
313         pPage->ParseContent();
314         return pPage;
315 }
316
317 DLLEXPORT double STDCALL FPDF_GetPageWidth(FPDF_PAGE page)
318 {
319         if (!page)
320                 return 0.0;
321         return ((CPDF_Page*)page)->GetPageWidth();
322 }
323
324 DLLEXPORT double STDCALL FPDF_GetPageHeight(FPDF_PAGE page)
325 {
326         if (!page) return 0.0;
327         return ((CPDF_Page*)page)->GetPageHeight();
328 }
329
330 void DropContext(void* data)
331 {
332         delete (CRenderContext*)data;
333 }
334
335 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
336                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  );
337 void (*Func_RenderPage)(CRenderContext*, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
338                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause  ) = FPDF_RenderPage_Retail;
339
340 #if defined(_DEBUG) || defined(DEBUG)
341 #define DEBUG_TRACE
342 #endif
343
344 #if defined(_WIN32)
345 DLLEXPORT void STDCALL FPDF_RenderPage(HDC dc, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
346                                                 int rotate, int flags)
347 {
348         if (page==NULL) return;
349         CPDF_Page* pPage = (CPDF_Page*)page;
350
351         CRenderContext* pContext = new CRenderContext;
352         pPage->SetPrivateData((void*)1, pContext, DropContext);
353
354 #ifndef _WIN32_WCE
355         CFX_DIBitmap* pBitmap = NULL;
356         FX_BOOL bBackgroundAlphaNeeded=FALSE;
357         bBackgroundAlphaNeeded = pPage->BackgroundAlphaNeeded();
358         if (bBackgroundAlphaNeeded)
359         {
360
361                 pBitmap = new CFX_DIBitmap;
362                 pBitmap->Create(size_x, size_y, FXDIB_Argb);
363                 pBitmap->Clear(0x00ffffff);
364 #ifdef _SKIA_SUPPORT_
365                 pContext->m_pDevice = new CFX_SkiaDevice;
366                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
367 #else
368                 pContext->m_pDevice = new CFX_FxgeDevice;
369                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)pBitmap);
370 #endif
371         }
372         else
373             pContext->m_pDevice = new CFX_WindowsDevice(dc);
374
375         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
376
377         if (bBackgroundAlphaNeeded)
378         {
379                 if (pBitmap)
380                 {
381                         CFX_WindowsDevice WinDC(dc);
382
383                         if (WinDC.GetDeviceCaps(FXDC_DEVICE_CLASS) == FXDC_PRINTER)
384                         {
385                                 CFX_DIBitmap* pDst = new CFX_DIBitmap;
386                                 int pitch = pBitmap->GetPitch();
387                                 pDst->Create(size_x, size_y, FXDIB_Rgb32);
388                                 FXSYS_memset(pDst->GetBuffer(), -1, pitch*size_y);
389                                 pDst->CompositeBitmap(0, 0, size_x, size_y, pBitmap, 0, 0, FXDIB_BLEND_NORMAL, NULL, FALSE, NULL);
390                                 WinDC.StretchDIBits(pDst,0,0,size_x,size_y);
391                                 delete pDst;
392                         }
393                         else
394                                 WinDC.SetDIBits(pBitmap,0,0);
395
396                 }
397         }
398 #else
399         // get clip region
400         RECT rect, cliprect;
401         rect.left = start_x;
402         rect.top = start_y;
403         rect.right = start_x + size_x;
404         rect.bottom = start_y + size_y;
405         GetClipBox(dc, &cliprect);
406         IntersectRect(&rect, &rect, &cliprect);
407         int width = rect.right - rect.left;
408         int height = rect.bottom - rect.top;
409
410 #ifdef DEBUG_TRACE
411         {
412                 char str[128];
413                 memset(str, 0, sizeof(str));
414                 FXSYS_snprintf(str, sizeof(str) - 1, "Rendering DIB %d x %d", width, height);
415                 CPDF_ModuleMgr::Get()->ReportError(999, str);
416         }
417 #endif
418
419         // Create a DIB section
420         LPVOID pBuffer;
421         BITMAPINFOHEADER bmih;
422         FXSYS_memset(&bmih, 0, sizeof bmih);
423         bmih.biSize = sizeof bmih;
424         bmih.biBitCount = 24;
425         bmih.biHeight = -height;
426         bmih.biPlanes = 1;
427         bmih.biWidth = width;
428         pContext->m_hBitmap = CreateDIBSection(dc, (BITMAPINFO*)&bmih, DIB_RGB_COLORS, &pBuffer, NULL, 0);
429         if (pContext->m_hBitmap == NULL) {
430 #if defined(DEBUG) || defined(_DEBUG)
431                 char str[128];
432                 memset(str, 0, sizeof(str));
433                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateDIBSection: %d x %d, error code = %d", width, height, GetLastError());
434                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
435 #else
436                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
437 #endif
438         }
439         FXSYS_memset(pBuffer, 0xff, height*((width*3+3)/4*4));
440
441 #ifdef DEBUG_TRACE
442         {
443                 CPDF_ModuleMgr::Get()->ReportError(999, "DIBSection created");
444         }
445 #endif
446
447         // Create a device with this external buffer
448         pContext->m_pBitmap = new CFX_DIBitmap;
449         pContext->m_pBitmap->Create(width, height, FXDIB_Rgb, (uint8_t*)pBuffer);
450         pContext->m_pDevice = new CPDF_FxgeDevice;
451         ((CPDF_FxgeDevice*)pContext->m_pDevice)->Attach(pContext->m_pBitmap);
452
453 #ifdef DEBUG_TRACE
454         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for PDF rendering");
455 #endif
456
457         // output to bitmap device
458         Func_RenderPage(pContext, page, start_x - rect.left, start_y - rect.top, size_x, size_y, rotate, flags);
459
460 #ifdef DEBUG_TRACE
461         CPDF_ModuleMgr::Get()->ReportError(999, "Finished PDF rendering");
462 #endif
463
464         // Now output to real device
465         HDC hMemDC = CreateCompatibleDC(dc);
466         if (hMemDC == NULL) {
467 #if defined(DEBUG) || defined(_DEBUG)
468                 char str[128];
469                 memset(str, 0, sizeof(str));
470                 FXSYS_snprintf(str, sizeof(str) - 1, "Error CreateCompatibleDC. Error code = %d", GetLastError());
471                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, str);
472 #else
473                 CPDF_ModuleMgr::Get()->ReportError(FPDFERR_OUT_OF_MEMORY, NULL);
474 #endif
475         }
476
477         HGDIOBJ hOldBitmap = SelectObject(hMemDC, pContext->m_hBitmap);
478
479 #ifdef DEBUG_TRACE
480         CPDF_ModuleMgr::Get()->ReportError(999, "Ready for screen rendering");
481 #endif
482
483         BitBlt(dc, rect.left, rect.top, width, height, hMemDC, 0, 0, SRCCOPY);
484         SelectObject(hMemDC, hOldBitmap);
485         DeleteDC(hMemDC);
486
487 #ifdef DEBUG_TRACE
488         CPDF_ModuleMgr::Get()->ReportError(999, "Finished screen rendering");
489 #endif
490
491 #endif
492         if (bBackgroundAlphaNeeded)
493         {
494                 if (pBitmap)
495                         delete pBitmap;
496                 pBitmap = NULL;
497         }
498         delete pContext;
499         pPage->RemovePrivateData((void*)1);
500 }
501 #endif
502
503 DLLEXPORT void STDCALL FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, FPDF_PAGE page, int start_x, int start_y,
504                                                 int size_x, int size_y, int rotate, int flags)
505 {
506         if (bitmap == NULL || page == NULL) return;
507         CPDF_Page* pPage = (CPDF_Page*)page;
508
509
510         CRenderContext* pContext = new CRenderContext;
511         pPage->SetPrivateData((void*)1, pContext, DropContext);
512 #ifdef _SKIA_SUPPORT_
513         pContext->m_pDevice = new CFX_SkiaDevice;
514
515         if (flags & FPDF_REVERSE_BYTE_ORDER)
516                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
517         else
518                 ((CFX_SkiaDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
519 #else
520         pContext->m_pDevice = new CFX_FxgeDevice;
521
522         if (flags & FPDF_REVERSE_BYTE_ORDER)
523                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap,0,TRUE);
524         else
525                 ((CFX_FxgeDevice*)pContext->m_pDevice)->Attach((CFX_DIBitmap*)bitmap);
526 #endif
527
528         Func_RenderPage(pContext, page, start_x, start_y, size_x, size_y, rotate, flags,TRUE,NULL);
529
530         delete pContext;
531         pPage->RemovePrivateData((void*)1);
532 }
533
534 DLLEXPORT void STDCALL FPDF_ClosePage(FPDF_PAGE page)
535 {
536         if (!page) return;
537         CPDFSDK_PageView* pPageView = (CPDFSDK_PageView*)(((CPDF_Page*)page))->GetPrivateData((void*)page);
538         if (pPageView && pPageView->IsLocked()) {
539             pPageView->TakeOverPage();
540             return;
541         }
542         delete (CPDF_Page*)page;
543
544 }
545
546 DLLEXPORT void STDCALL FPDF_CloseDocument(FPDF_DOCUMENT document)
547 {
548         if (!document)
549                 return;
550         CPDF_Document* pDoc = (CPDF_Document*)document;
551         CPDF_Parser* pParser = (CPDF_Parser*)pDoc->GetParser();
552         if (pParser == NULL)
553         {
554                 delete pDoc;
555                 return;
556         }
557         delete pParser;
558 //      delete pDoc;
559 }
560
561 DLLEXPORT unsigned long STDCALL FPDF_GetLastError()
562 {
563         return GetLastError();
564 }
565
566 DLLEXPORT void STDCALL FPDF_DeviceToPage(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
567                                                 int rotate, int device_x, int device_y, double* page_x, double* page_y)
568 {
569         if (page == NULL || page_x == NULL || page_y == NULL) return;
570         CPDF_Page* pPage = (CPDF_Page*)page;
571
572         CPDF_Matrix page2device;
573         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
574         CPDF_Matrix device2page;
575         device2page.SetReverse(page2device);
576
577         FX_FLOAT page_x_f, page_y_f;
578         device2page.Transform((FX_FLOAT)(device_x), (FX_FLOAT)(device_y), page_x_f, page_y_f);
579
580         *page_x = (page_x_f);
581         *page_y = (page_y_f);
582 }
583
584 DLLEXPORT void STDCALL FPDF_PageToDevice(FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
585                                                 int rotate, double page_x, double page_y, int* device_x, int* device_y)
586 {
587         if (page == NULL || device_x == NULL || device_y == NULL) return;
588         CPDF_Page* pPage = (CPDF_Page*)page;
589
590         CPDF_Matrix page2device;
591         pPage->GetDisplayMatrix(page2device, start_x, start_y, size_x, size_y, rotate);
592
593         FX_FLOAT device_x_f, device_y_f;
594         page2device.Transform(((FX_FLOAT)page_x), ((FX_FLOAT)page_y), device_x_f, device_y_f);
595
596         *device_x = FXSYS_round(device_x_f);
597         *device_y = FXSYS_round(device_y_f);
598 }
599
600 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_Create(int width, int height, int alpha)
601 {
602     nonstd::unique_ptr<CFX_DIBitmap> pBitmap(new CFX_DIBitmap);
603     if (!pBitmap->Create(width, height, alpha ? FXDIB_Argb : FXDIB_Rgb32)) {
604         return NULL;
605     }
606     return pBitmap.release();
607 }
608
609 DLLEXPORT FPDF_BITMAP STDCALL FPDFBitmap_CreateEx(int width, int height, int format, void* first_scan, int stride)
610 {
611         FXDIB_Format fx_format;
612         switch (format) {
613                 case FPDFBitmap_Gray:
614                         fx_format = FXDIB_8bppRgb;
615                         break;
616                 case FPDFBitmap_BGR:
617                         fx_format = FXDIB_Rgb;
618                         break;
619                 case FPDFBitmap_BGRx:
620                         fx_format = FXDIB_Rgb32;
621                         break;
622                 case FPDFBitmap_BGRA:
623                         fx_format = FXDIB_Argb;
624                         break;
625                 default:
626                         return NULL;
627         }
628         CFX_DIBitmap* pBitmap = new CFX_DIBitmap;
629         pBitmap->Create(width, height, fx_format, (uint8_t*)first_scan, stride);
630         return pBitmap;
631 }
632
633 DLLEXPORT void STDCALL FPDFBitmap_FillRect(FPDF_BITMAP bitmap, int left, int top, int width, int height, FPDF_DWORD color)
634 {
635         if (bitmap == NULL) return;
636 #ifdef _SKIA_SUPPORT_
637         CFX_SkiaDevice device;
638 #else
639         CFX_FxgeDevice device;
640 #endif
641         device.Attach((CFX_DIBitmap*)bitmap);
642         if (!((CFX_DIBitmap*)bitmap)->HasAlpha()) color |= 0xFF000000;
643         FX_RECT rect(left, top, left+width, top+height);
644         device.FillRect(&rect, color);
645 }
646
647 DLLEXPORT void* STDCALL FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap)
648 {
649         if (bitmap == NULL) return NULL;
650         return ((CFX_DIBitmap*)bitmap)->GetBuffer();
651 }
652
653 DLLEXPORT int STDCALL FPDFBitmap_GetWidth(FPDF_BITMAP bitmap)
654 {
655         if (bitmap == NULL) return 0;
656         return ((CFX_DIBitmap*)bitmap)->GetWidth();
657 }
658
659 DLLEXPORT int STDCALL FPDFBitmap_GetHeight(FPDF_BITMAP bitmap)
660 {
661         if (bitmap == NULL) return 0;
662         return ((CFX_DIBitmap*)bitmap)->GetHeight();
663 }
664
665 DLLEXPORT int STDCALL FPDFBitmap_GetStride(FPDF_BITMAP bitmap)
666 {
667         if (bitmap == NULL) return 0;
668         return ((CFX_DIBitmap*)bitmap)->GetPitch();
669 }
670
671 DLLEXPORT void STDCALL FPDFBitmap_Destroy(FPDF_BITMAP bitmap)
672 {
673         if (bitmap == NULL) return;
674         delete (CFX_DIBitmap*)bitmap;
675 }
676
677 void FPDF_RenderPage_Retail(CRenderContext* pContext, FPDF_PAGE page, int start_x, int start_y, int size_x, int size_y,
678                                                 int rotate, int flags,FX_BOOL bNeedToRestore, IFSDK_PAUSE_Adapter * pause )
679 {
680         CPDF_Page* pPage = (CPDF_Page*)page;
681         if (pPage == NULL) return;
682
683         if (!pContext->m_pOptions)
684                 pContext->m_pOptions = new CPDF_RenderOptions;
685 //      CPDF_RenderOptions options;
686         if (flags & FPDF_LCD_TEXT)
687                 pContext->m_pOptions->m_Flags |= RENDER_CLEARTYPE;
688         else
689                 pContext->m_pOptions->m_Flags &= ~RENDER_CLEARTYPE;
690         if (flags & FPDF_NO_NATIVETEXT)
691                 pContext->m_pOptions->m_Flags |= RENDER_NO_NATIVETEXT;
692         if (flags & FPDF_RENDER_LIMITEDIMAGECACHE)
693                 pContext->m_pOptions->m_Flags |= RENDER_LIMITEDIMAGECACHE;
694         if (flags & FPDF_RENDER_FORCEHALFTONE)
695                 pContext->m_pOptions->m_Flags |= RENDER_FORCE_HALFTONE;
696         if (flags & FPDF_RENDER_NO_SMOOTHTEXT)
697                 pContext->m_pOptions->m_Flags |= RENDER_NOTEXTSMOOTH;
698         if (flags & FPDF_RENDER_NO_SMOOTHIMAGE)
699                 pContext->m_pOptions->m_Flags |= RENDER_NOIMAGESMOOTH;
700         if (flags & FPDF_RENDER_NO_SMOOTHPATH)
701                 pContext->m_pOptions->m_Flags |= RENDER_NOPATHSMOOTH;
702         //Grayscale output
703         if (flags & FPDF_GRAYSCALE)
704         {
705                 pContext->m_pOptions->m_ColorMode = RENDER_COLOR_GRAY;
706                 pContext->m_pOptions->m_ForeColor = 0;
707                 pContext->m_pOptions->m_BackColor = 0xffffff;
708         }
709         const CPDF_OCContext::UsageType usage = (flags & FPDF_PRINTING) ? CPDF_OCContext::Print : CPDF_OCContext::View;
710
711         pContext->m_pOptions->m_AddFlags = flags >> 8;
712
713         pContext->m_pOptions->m_pOCContext = new CPDF_OCContext(pPage->m_pDocument, usage);
714
715
716         CFX_AffineMatrix matrix;
717         pPage->GetDisplayMatrix(matrix, start_x, start_y, size_x, size_y, rotate);
718
719         FX_RECT clip;
720         clip.left = start_x;
721         clip.right = start_x + size_x;
722         clip.top = start_y;
723         clip.bottom = start_y + size_y;
724         pContext->m_pDevice->SaveState();
725         pContext->m_pDevice->SetClip_Rect(&clip);
726
727         pContext->m_pContext = new CPDF_RenderContext;
728         pContext->m_pContext->Create(pPage);
729         pContext->m_pContext->AppendObjectList(pPage, &matrix);
730
731         if (flags & FPDF_ANNOT) {
732                 pContext->m_pAnnots = new CPDF_AnnotList(pPage);
733                 FX_BOOL bPrinting = pContext->m_pDevice->GetDeviceClass() != FXDC_DISPLAY;
734                 pContext->m_pAnnots->DisplayAnnots(pPage, pContext->m_pContext, bPrinting, &matrix, TRUE, NULL);
735         }
736
737         pContext->m_pRenderer = new CPDF_ProgressiveRenderer;
738         pContext->m_pRenderer->Start(pContext->m_pContext, pContext->m_pDevice, pContext->m_pOptions, pause);
739         if (bNeedToRestore)
740         {
741           pContext->m_pDevice->RestoreState();
742         }
743 }
744
745 DLLEXPORT int STDCALL FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, int page_index, double* width, double* height)
746 {
747         CPDF_Document* pDoc = (CPDF_Document*)document;
748         if(pDoc == NULL)
749                 return FALSE;
750
751         CPDF_Dictionary* pDict = pDoc->GetPage(page_index);
752         if (pDict == NULL) return FALSE;
753
754         CPDF_Page page;
755         page.Load(pDoc, pDict);
756         *width = page.GetPageWidth();
757         *height = page.GetPageHeight();
758
759         return TRUE;
760 }
761
762 DLLEXPORT FPDF_BOOL STDCALL FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document)
763 {
764         CPDF_Document* pDoc = (CPDF_Document*)document;
765         if (!pDoc) return TRUE;
766         CPDF_ViewerPreferences viewRef(pDoc);
767         return viewRef.PrintScaling();
768 }
769
770 DLLEXPORT int STDCALL FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document)
771 {
772     CPDF_Document* pDoc = (CPDF_Document*)document;
773     if (!pDoc) return 1;
774     CPDF_ViewerPreferences viewRef(pDoc);
775     return viewRef.NumCopies();
776 }
777
778 DLLEXPORT FPDF_PAGERANGE STDCALL FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document)
779 {
780     CPDF_Document* pDoc = (CPDF_Document*)document;
781     if (!pDoc) return NULL;
782     CPDF_ViewerPreferences viewRef(pDoc);
783     return viewRef.PrintPageRange();
784 }
785
786 DLLEXPORT FPDF_DUPLEXTYPE STDCALL FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document)
787 {
788     CPDF_Document* pDoc = (CPDF_Document*)document;
789     if (!pDoc) return DuplexUndefined;
790     CPDF_ViewerPreferences viewRef(pDoc);
791     CFX_ByteString duplex = viewRef.Duplex();
792     if (FX_BSTRC("Simplex") == duplex)
793         return Simplex;
794     if (FX_BSTRC("DuplexFlipShortEdge") == duplex)
795         return DuplexFlipShortEdge;
796     if (FX_BSTRC("DuplexFlipLongEdge") == duplex)
797         return DuplexFlipLongEdge;
798     return DuplexUndefined;
799 }
800
801 DLLEXPORT FPDF_DWORD STDCALL FPDF_CountNamedDests(FPDF_DOCUMENT document)
802 {
803     if (!document) return 0;
804     CPDF_Document* pDoc = (CPDF_Document*)document;
805
806     CPDF_Dictionary* pRoot = pDoc->GetRoot();
807     if (!pRoot) return 0;
808
809     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
810     int count = nameTree.GetCount();
811     CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
812     if (pDest)
813         count += pDest->GetCount();
814     return count;
815 }
816
817 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDestByName(FPDF_DOCUMENT document,FPDF_BYTESTRING name)
818 {
819         if (!document)
820                 return NULL;
821         if (!name || name[0] == 0)
822                 return NULL;
823
824         CPDF_Document* pDoc = (CPDF_Document*)document;
825         CPDF_NameTree name_tree(pDoc, FX_BSTRC("Dests"));
826         return name_tree.LookupNamedDest(pDoc, name);
827 }
828
829 DLLEXPORT FPDF_DEST STDCALL FPDF_GetNamedDest(FPDF_DOCUMENT document, int index, void* buffer, long* buflen)
830 {
831     if (!buffer)
832         *buflen = 0;
833     if (!document || index < 0) return NULL;
834     CPDF_Document* pDoc = (CPDF_Document*)document;
835
836     CPDF_Dictionary* pRoot = pDoc->GetRoot();
837     if (!pRoot) return NULL;
838
839     CPDF_Object* pDestObj = NULL;
840     CFX_ByteString bsName;
841     CPDF_NameTree nameTree(pDoc, FX_BSTRC("Dests"));
842     int count = nameTree.GetCount();
843     if (index >= count) {
844         CPDF_Dictionary* pDest = pRoot->GetDict(FX_BSTRC("Dests"));
845         if (!pDest) return NULL;
846         if (index >= count + pDest->GetCount()) return NULL;
847         index -= count;
848         FX_POSITION pos = pDest->GetStartPos();
849         int i = 0;
850         while (pos) {
851             pDestObj = pDest->GetNextElement(pos, bsName);
852             if (!pDestObj) continue;
853             if (i == index) break;
854             i++;
855         }
856     } else {
857         pDestObj = nameTree.LookupValue(index, bsName);
858     }
859     if (!pDestObj) return NULL;
860     if (pDestObj->GetType() == PDFOBJ_DICTIONARY) {
861         pDestObj = ((CPDF_Dictionary*)pDestObj)->GetArray(FX_BSTRC("D"));
862         if (!pDestObj) return NULL;
863     }
864     if (pDestObj->GetType() != PDFOBJ_ARRAY) return NULL;
865     CFX_WideString wsName = PDF_DecodeText(bsName);
866     CFX_ByteString utf16Name = wsName.UTF16LE_Encode();
867     unsigned int len = utf16Name.GetLength();
868     if (!buffer) {
869         *buflen = len;
870     } else if (*buflen >= len) {
871         memcpy(buffer, utf16Name.c_str(), len);
872         *buflen = len;
873     } else {
874         *buflen = -1;
875     }
876     return (FPDF_DEST)pDestObj;
877 }