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